代码之家  ›  专栏  ›  技术社区  ›  Guerric P

泛型推理

  •  0
  • Guerric P  · 技术社区  · 4 年前

    在本例中:

    type MyType = 'val1' | 'val2' | 'val3';
    
    const variable = 'val1' as MyType;
    
    const val2 = 'val2';
    const val3 = 'val3';
    
    declare function test<U extends MyType>(...args: U[]): void;
    
    test(val2, val3); // U successfully resolves to "val3" | "val2"
    
    declare function test2<T, U extends T>(value: T | undefined, ...values: U[]): void;
    
    test2(variable, val2, val3); // U gets widened to "val1" | "val2" | "val3"
    

    两者都有 test test2 , U extends MyType .

    那么我想 测试2 解决 U "val3" | "val2" 就像当年一样 测验 ,但事实并非如此。

    为什么?

    TypeScript playground

    0 回复  |  直到 4 年前
        1
  •  1
  •   Olian04    4 年前

    我认为这是一个类型系统偷工减料的例子。Typescript被允许时不时地在类型检查上走捷径。尤其是如果它能够检测到生成的类型不会在类型系统的其他地方使用。我想typescript确认了 "val1" | "val2" | "val3" 对于参数列表来说已经足够好了。 然而,假设我们改变了 test2 从…起 void U .然后,因为 U 预计将返回并可能在typescript中的其他地方使用,编译器将需要花费更多时间来解析实际/最窄的类型 U .

    type MyType = 'val1' | 'val2' | 'val3';
    
    const variable = 'val1' as MyType;
    
    const val2 = 'val2';
    const val3 = 'val3';
    
    declare function test2<T, U extends T>(value: T | undefined, ...values: U[]): void;
    
    test2(variable, val2, val3); // U gets widened to "val1" | "val2" | "val3"
    
    declare function test3<T, U extends T>(value: T | undefined, ...values: U[]): U;
    
    test3(variable, val2, val3); // U successfully resolves to "val3" | "val2"
    

    playground

    推荐文章