在 TypeScript 中定义具有多种类型的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29382389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Defining array with multiple types in TypeScript
提问by dk123
I have an array of the form: [ 1, "message" ]
.
我有一个以下形式的数组:[ 1, "message" ]
.
How would I define this in TypeScript?
我将如何在 TypeScript 中定义它?
回答by basarat
Defining array with multiple types in TypeScript
在 TypeScript 中定义具有多种类型的数组
Use a union type (string|number)[]
demo:
使用联合类型(string|number)[]
演示:
const foo: (string|number)[] = [ 1, "message" ];
I have an array of the form: [ 1, "message" ].
我有一个以下形式的数组:[ 1, "message" ]。
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
如果您确定始终只有两个元素,[number, string]
则可以将其声明为元组:
const foo: [number, string] = [ 1, "message" ];
回答by curpa
If you're treating it as a tuple (see section 3.3.3 of the language spec), then:
如果您将其视为元组(请参阅语言规范的第 3.3.3 节),则:
var t:[number, string] = [1, "message"]
or
或者
interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];
回答by Szamanm
My TS lint was complaining about other solutions, so the solution that was working for me was:
我的 TS lint 抱怨其他解决方案,所以对我有用的解决方案是:
item: Array<Type1 | Type2>
if there's only one type, it's fine to use:
如果只有一种类型,可以使用:
item: Type1[]
回答by j4ys0n
I've settled on the following format for typing arrays that can have items of multiple types.
我已经确定了以下格式来键入可以包含多种类型项目的数组。
Array<ItemType1 | ItemType2 | ItemType3>
Array<ItemType1 | ItemType2 | ItemType3>
This works well with testing and type guards. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
这适用于测试和类型保护。https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
This format doesn't work well with testing or type guards:
这种格式不适用于测试或类型保护:
(ItemType1 | ItemType2 | ItemType3)[]
(ItemType1 | ItemType2 | ItemType3)[]
回答by DerKarim
Im using this version:
我正在使用这个版本:
exampleArr: Array<{ id: number, msg: string}> = [
{ id: 1, msg: 'message'},
{ id: 2, msg: 'message2'}
]
It is a little bit similar to the other suggestions but still easy and quite good to remember.
它与其他建议有点相似,但仍然很容易记住。