简体   繁体   English

在 TypeScript 中输入具有联合类型的数组?

[英]Typing an Array with a union type in TypeScript?

I was just wondering if it is possible to type array with a union type, so that one array can contain both Apples and Oranges but nothing else.我只是想知道是否可以使用联合类型键入数组,以便一个数组可以同时包含 Apples 和 Oranges,但不能包含其他任何内容。

Something like就像是

var arr : (Apple|Orange)[] = [];

arr.push(apple); //ok
arr.push(orange); //ok
arr.push(1); //error
arr.push("abc"); // error

Needless to say, the example above does not work so this may not be possible, or am I missing something?不用说,上面的例子不起作用,所以这可能是不可能的,或者我错过了什么?

class Apple {
  appleFoo: any;
}

class Orange {
  orangeFoo: any;
}

var arr : Array<Apple|Orange> = [];

var apple = new Apple();
var orange = new Orange();

arr.push(apple); //ok
arr.push(orange); //ok
arr.push(1); //error
arr.push("abc"); // error

var something = arr[0];

if(something instanceof Apple) {
  something.appleFoo; //ok
  something.orangeFoo; //error
} else if(something instanceof Orange) {
  something.appleFoo; //error
  something.orangeFoo; //ok
}

As per TS 2.3.4 is as simple as根据 TS 2.3.4 就像这样简单

let someArray: (typeA|typeB)[] = [
  new typeA(),
  new typeB()
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM