coloud
coloud

Reputation: 41

Typescript type inference doesn't work in conditional type

type A = "a" | "b";
type B = "c" | "d";
type C<Type extends A> = Type;
type D<Type extends B> = Type;
type Auto<Type extends (A|B)> = Type extends A ? C<Type> : D<Type>; //It throws error!
//Type 'Type' does not satisfy the constraint 'B'.

Auto type has generic. Type is A|B, same as "a" | "b" | "c" | "d". And A is equal to "a" | "b". But why I can't use Type extends A ? C<Type> : D<Type>? D<Type> throws error "Type 'Type' does not satisfy the constraint 'B'.".

Upvotes: 0

Views: 157

Answers (1)

jcalz
jcalz

Reputation: 330571

This is an open issue; see microsoft/TypeScript#23132. You may want to give that issue a 👍 or describe your use case if you think it's compelling. Not sure if it will ever be changed. For now, though, conditional types more or less ignore any generic constraint and the workaround is to use additional and possibly redundant checks:

type Auto<T extends (A | B)> = T extends A ? C<T> : T extends B ? D<T> : never

That should behave the way you want it to. Okay, hope that helps; good luck!

Playground link to code

Upvotes: 2

Related Questions