admin管理员组

文章数量:1310747

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

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

Share Improve this question edited Feb 2 at 9:36 Xunnamius asked Feb 2 at 9:22 XunnamiusXunnamius 5781 gold badge9 silver badges17 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 3

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';

本文标签: