![](/img/trans.png)
[英]Typing recursive function with union return type in typescript
[英]Typing an Array with a union type in TypeScript?
我只是想知道是否可以使用联合类型键入数组,以便一个数组可以同时包含 Apples 和 Oranges,但不能包含其他任何内容。
就像是
var arr : (Apple|Orange)[] = [];
arr.push(apple); //ok
arr.push(orange); //ok
arr.push(1); //error
arr.push("abc"); // error
不用说,上面的例子不起作用,所以这可能是不可能的,或者我错过了什么?
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
}
根据 TS 2.3.4 就像这样简单
let someArray: (typeA|typeB)[] = [
new typeA(),
new typeB()
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.