pfgray / ts-adt

Generate Algebraic Data Types and pattern matchers
MIT License
314 stars 13 forks source link

Type inferring issue for Partial Matchers with Custom Discriminant field #22

Closed laperla closed 3 years ago

laperla commented 3 years ago

I'm having some trouble making these partial matchers for my ADTs, for example:

const matchOptionPI = makeMatchPI("_tag")
matchOptionPI(fromNullable("value"))(
{
    None: () => 0
},
// Here 'some' is inferred as Option<string>, so 'value' doesn't exist on type None 
(some) => some.value)

This code also notifies an error on my IDE:

type Xor<A, B> =
  | { tipo: "nothing" }
  | { tipo: "left", value: A }
  | { tipo: "right", value: B}  

  declare const myXor: Xor<number, string>

  const xorMatchPI = makeMatchPI("tipo")

// Here 'rest' is inferred as Xor<number, string>, so 'value' doesn't exist on type { tipo:"nothing" } 
  xorMatchPI(myXor)({nothing: () => 0 }, (rest) => rest.value)

But it works when the discriminant field has the default value "_type":

  type Xor<A, B> =
  | { _type: "nothing" }
  | { _type: "left", value: A }
  | { _type: "right", value: B}  

  declare const myXor: Xor<number, string>

  const xorMatchPI = makeMatchPI("_type")

// Here 'rest' is inferred correctly as {_type: 'left', value: number } | {_type: 'right', value: string }
  xorMatchPI(myXor)({ nothing: () => 0 }, (rest) => rest.value)
pfgray commented 3 years ago

Ah, I think this was left over from the non-customizable types, just pushed a fix, thanks!