typescripttypescript-genericstype-inference

Why is TypeScript having trouble conditionally inferring optional elements at the end of an array?


I was considering opening an issue against the TypeScript repo directly, but I'm hoping the answer is obvious.

Why does the following conditional type result in 'BAD'?

type X = [string[], string[], {
  a?: boolean;
  b?: boolean;
}?] extends [...infer A, infer B] ? B : 'BAD';

// A == 'BAD'
// B == 'BAD'

However, if I make the final element non-optional, or move the optional element to the middle or beginning of the array (which is unsound (TS1257) but still satisfies the condition for the purposes of this example), it extends and infers as expected:

type Y = [string[], string[], {
  a?: boolean;
  b?: boolean;
}] extends [...infer A, infer B] ? B : 'BAD';

// A == [string[], string[]]
// B == { a?: boolean; b?: boolean; }

// This triggers TS1257 (as mentioned above) but mousing over Z in the playground
// still yields the correct inference:
type Z = [string[], {
  a?: boolean;
  b?: boolean;
}?, string[]] extends [...infer A, infer B] ? B : 'BAD';

// A == [string[], { a?: boolean; b?: boolean; } | undefined]
// B == string[]

Playground link


Solution

  • It's hacky but works, basically you imitate your "invalid" case with a required element after the optional, TS doesn't complain. What happens: when the last element is optional, TS cannot infer the proper tuple's length, since it's dynamic. Given the last required element, the tuple acquires a static length:

    Playground

    type X = ExtractLast<[string[], string[], {
      // ^?
      a?: boolean;
      b?: boolean;
    }?]>
    
    type ExtractLast<T extends unknown[]> = [...T, unknown] extends [...unknown[], infer B, unknown] ? B : 'BAD';