Typing an Array with a union type in TypeScript?

daniel.sedlacek picture daniel.sedlacek · Apr 22, 2015 · Viewed 17k times · Source

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.

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?

Answer

danielnixon picture danielnixon · Apr 22, 2015
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
}