【问题标题】:How to convert a tuple type to a union?如何将元组类型转换为联合?
【发布时间】:2020-04-02 00:15:31
【问题描述】:

如何将元组泛型类型映射到联合类型?

type NeededUnionType<T> = T[keyof T]; // Includes all the Array properties values
  
const value: NeededUnionType<[7, string]> = 2; // This should not be allowed (2 is the tuple length)

预期类型:7 | string

【问题讨论】:

    标签: typescript tuples typescript-generics union-types mapped-types


    【解决方案1】:

    您可以使用number 而非keyof T 进行索引。 keyof T 将包含元组对象的所有键,其中包括长度以及任何其他数组属性。

    type NeededUnionType<T extends any[]> = T[number]; // Includes all the Array properties values
    
    const value: NeededUnionType<[7, string]> = 2; // err value is 7 | string 
    
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2020-06-04
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多