Typing an Array with a union type in TypeScript?
As per TS 2.3.4 is as simple as
let someArray: (typeA|typeB)[] = [
new typeA(),
new typeB()
]
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
}