在 TypeScript 中定义具有多种类型的数组 [英] Defining array with multiple types in TypeScript
问题描述
我有一个如下形式的数组:[ 1, "message" ]
.
我将如何在 TypeScript 中定义它?
在 TypeScript 中定义多类型数组
使用联合类型(string|number)[]
演示:
const foo: (string|number)[] = [ 1, message";];
<块引用>
我有一个如下形式的数组:[ 1, message";].
如果你确定总是只有两个元素 [number, string]
那么你可以将它声明为一个元组:
const foo: [number, string] = [ 1, message";];
重要提示
当您想访问仅在其中一种类型上可用的属性时,这不适用于具有不同属性的复杂类型.
I have an array of the form: [ 1, "message" ]
.
How would I define this in TypeScript?
Defining array with multiple types in TypeScript
Use a union type (string|number)[]
demo:
const foo: (string|number)[] = [ 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" ];
IMPORTANT NOTE
This won't work with complex types with different properties, when you want to access a property available on only one of the types.
这篇关于在 TypeScript 中定义具有多种类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!