Typing an Array with a union type in TypeScript?

和自甴很熟 提交于 2019-12-30 08:05:28

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/29794014/typing-an-array-with-a-union-type-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!