Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining array with multiple types in TypeScript

I have an array of the form: [ 1, "message" ].

How would I define this in TypeScript?

like image 770
dk123 Avatar asked Apr 01 '15 03:04

dk123


People also ask

How do you create an array with multiple data types in TypeScript?

Use a union type to define an array with multiple types in TypeScript, e.g. const arr: (string | number)[] = ['a', 1] . A union type is formed from two or more other types. The array in the example can only contain values of type string and number .

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.

Can you have array with multiple types?

You can create an array with elements of different data types when declare the array as Object. Since System. Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.

How do I assign two TypeScript types?

TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.


1 Answers

Defining array with multiple types in TypeScript

Use a union type (string|number)[] demo:

const foo: (string|number)[] = [ 1, "message" ]; 

I have an array of the form: [ 1, "message" ].

If you are sure that there are always only two elements [number, string] then you can declare it as a tuple:

const foo: [number, string] = [ 1, "message" ]; 

IMPORTANT NOTE

This won't work with complex types with different properties, when you want to access a property available on only one of the types.

See this newer answer.

like image 189
basarat Avatar answered Sep 22 '22 18:09

basarat