Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typing an Array with a union type in TypeScript?

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?

like image 239
daniel.sedlacek Avatar asked Apr 22 '15 09:04

daniel.sedlacek


People also ask

How do you handle a union type in TypeScript?

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.

How do you declare a union type variable in TypeScript?

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.

How do you declare an array of types in TypeScript?

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.

How do you define a union in TypeScript?

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.


2 Answers

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
}
like image 81
danielnixon Avatar answered Oct 01 '22 05:10

danielnixon


As per TS 2.3.4 is as simple as

let someArray: (typeA|typeB)[] = [
  new typeA(),
  new typeB()
]
like image 28
Tomas Avatar answered Oct 01 '22 04:10

Tomas