如何将元组类型转换为联合?

use*_*988 7 tuples typescript typescript-generics union-types mapped-types

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

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)
Run Code Online (Sandbox Code Playgroud)

预期类型: 7 | string

Tit*_*mir 13

您可以索引number而不是keyof Tkeyof 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 

Run Code Online (Sandbox Code Playgroud)

游乐场链接