代码之家  ›  专栏  ›  技术社区  ›  Shaun Luttin

为什么来自任何[]的元组推断会变成[string,string,…],而来自string[]的元组推断会变成['literal1','literal2',…]

  •  2
  • Shaun Luttin  · 技术社区  · 6 年前

    我读过这个答案 https://stackoverflow.com/a/45486495/1108891 ,它演示了元组类型推断。经过一些实验,我遇到了这个场景。


    当我们 tuple T extends string[] 字符串文字 类型。

    export const tuple_0 = <T extends string[]>(...args: T): T => args;
    
    const ALL_SUITS_0 = tuple_0('hearts', 'diamonds', 'spades', 'clubs');
    
    type T0 = typeof ALL_SUITS_0; // ["hearts", "diamonds", "spades", "clubs"]
    

    T extends any[] ,元组具有 类型(不是文字)。

    export const tuple_1 = <T extends any[]>(...args: T) => args;
    
    const ALL_SUITS_1 = tuple_1('hearts', 'diamonds', 'spades', 'clubs');
    
    type T1 = typeof ALL_SUITS_1; // [string, string, string, string]
    

    为什么在后一种情况下会丢失文本类型?


    any 还有一步呢 string ,及 还有一步呢 'some-string-literal' . 类型推断是否只允许自己进行一步?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Shaun Luttin    6 年前

    这并不一定是特定于元组的。如果类型参数具有可以具有文字类型的约束,则Typescript将推断泛型参数的文字类型。这个行为是由这个 PR

    公共关系部:

    在调用表达式的类型参数推断过程中,如果[…],则为类型参数T推断的类型将加宽为其加宽的文字类型 T 没有约束或其约束不包括基元或文字类型

    在你问题的例子中,因为 string 是原始的,我们不加宽,自 any 这不是原始的,我们确实是加宽了。

    推荐文章