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

标签 typescript tuples 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)
预期类型:7 | string

最佳答案

您可以通过 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

关于typescript - 如何将元组类型转换为联合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59239632/

相关文章:

typescript - 键在应该用于索引类型时却不能使用

typescript - 如何在 TypeScript 中使一种泛型类型紧密依赖于另一种泛型类型?

javascript - ReactJS中ClassicComponentClass和ComponentClass的区别

java - 检查java中字典中是否存在元组键

python - 如何将元组的元组转换为列表列表?

angular - RxJS、Typescript 和可怕的 'Type Mismatch' 警告/错误

angular - 购物 list 未列出/保存超过 1 个食谱

typescript - Vim 不读取 TypeScript 文件

python - 如何在python中将每对列表转换为元组

TypeScript 泛型 "extends"约束 : Is there a nullable constraint?