Entering an array with a union type in TypeScript?

I'm just wondering if it is possible to type an array with a unifying type so that one array can contain both apples and oranges, but nothing more.

Sort of

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

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

Needless to say, the above example does not work, so it may not be possible, or am I missing something?

+9
source share
1 answer
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
}
+15
source

Source: https://habr.com/ru/post/1583980/


All Articles