在TypeScript中定义具有多种类型的数组 [英] Defining array with multiple types in TypeScript
本文介绍了在TypeScript中定义具有多种类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个格式如下的数组: [1,"message"]
.
I have an array of the form: [ 1, "message" ]
.
如何在TypeScript中定义它?
How would I define this in TypeScript?
推荐答案
在TypeScript中定义具有多种类型的数组
Defining array with multiple types in TypeScript
使用联合类型(string | number)[]
演示:
const foo: (string|number)[] = [ 1, "message" ];
我有一个以下形式的数组:[1,"message"].
I have an array of the form: [ 1, "message" ].
如果您确定总是只有两个元素 [数字,字符串]
,则可以将其声明为元组:
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
const foo: [number, string] = [ 1, "message" ];
这篇关于在TypeScript中定义具有多种类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文