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?
TypeScript Union Type Narrowing To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.
TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type.
Summary. In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.
In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ( '|' ) symbol between the types. The union types help in some special situations.
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
}
As per TS 2.3.4 is as simple as
let someArray: (typeA|typeB)[] = [
new typeA(),
new typeB()
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With