本文介绍了如何将元组类型转换为联合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将元组泛型类型映射到联合类型?
How to map a tuple generic type to a union type?
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 |字符串
推荐答案您可以通过 number 而不是 keyof T 来索引.keyof T 将包含元组对象的所有键,包括长度以及任何其他数组属性.
You can index by number instead of keyof T. keyof T will contain all keys of the tuple object which includes the length as well as any other array properties.
type NeededUnionType<T extends any[]> = T[number]; // Includes all the Array properties values const value: NeededUnionType<[7, string]> = 2; // err value is 7 | string游乐场链接
更多推荐
如何将元组类型转换为联合?
发布评论