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

编程入门 行业动态 更新时间:2024-10-28 10:32:14
本文介绍了如何将元组类型转换为联合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

游乐场链接

更多推荐

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

本文发布于:2023-07-13 03:26:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1099801.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!