Typescript 类型推断在条件类型中不起作用

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 类型具有泛型。 TypeA|B,与 "a" | "b" | "c" | "d" 相同。而 A 等于 "a" | "b"。但是为什么我不能使用Type extends A ? C<Type> : D<Type>呢? D<Type> 抛出错误 "Type 'Type' does not satisfy the constraint 'B'."。

这是一个悬而未决的问题;参见 microsoft/TypeScript#23132。如果您认为它很有说服力,您可能想提出该问题或描述您的用例。不确定它是否会被更改。不过,就目前而言,条件类型或多或少会忽略任何通用约束,解决方法是使用额外的且可能是冗余的检查:

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

这应该按照您希望的方式运行。好的,希望有所帮助;祝你好运!

Playground link to code