【问题标题】:Typescript type inference doesn't work in conditional typeTypescript 类型推断在条件类型中不起作用
【发布时间】:2020-03-03 01:54:47
【问题描述】:
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&lt;Type&gt; : D&lt;Type&gt;D&lt;Type&gt; 抛出错误“类型‘类型’不满足约束‘B’。”。

【问题讨论】:

    标签: typescript generics conditional-types


    【解决方案1】:

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

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

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

    Playground link to code

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2020-12-24
      • 2020-09-22
      • 1970-01-01
      • 2023-03-05
      • 2019-09-17
      • 1970-01-01
      • 2018-07-03
      • 2017-03-08
      相关资源
      最近更新 更多