Open In App

Defining array with multiple types in TypeScript

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript is a statically typed language. So, we can create an array with explicit types to store entries of only specified types inside it. If an array is declared with only one explicit data type specified, then we can store the data of that particular data type inside that array. If you try to store data of some other data type it throws an error. In this article, we will learn about the different ways of defining an array with multiple types in TypeScript.

The methods listed below can be used to define an array with multiple types in TypeScript:

Using the Union Type

A union type is created by defining multiple explicit data types separated by a vertical bar (|) inside parentheses. This union type is then used to explicitly type the array, allowing it to hold elements of any of the specified types at any index.

Syntax:

let array_name: (type1 | type2 | type3)[] = [];

Example: The below code example will illustrate the use of the union type to define an array with multiple types.

JavaScript
const myArr1: (string | number)[] = [1,
	"GeeksforGeeks", 2, "TypeScript"];
const myArr2: (string | number | boolean)[] = [1,
	"GeeksforGeeks", 2, true, "TypeScript", false];
console.log(myArr1);
console.log(myArr2);

Output:

[1, "GeeksforGeeks", 2, "TypeScript"] 
[1, "GeeksforGeeks", 2, true, "TypeScript", false]

Using a Tuple

A tuple is created by defining the explicit types inside the square brackets separated using commas(,). A tuple is used to create an array with a pre-defined length and type of element at each position in a specified order. It will throw an error if the type of element at a particular position is not the same as the specified type or if the length of the array differs.

Syntax:

const array_name: [type1, type2] = [];

Example: The below example will explain the use of a tuple to define an array with multiple data types and giving error while using wrong value.

JavaScript
const myArr1: [string, number] =
	["GeeksforGeeks", 1];
const myArr2: [number, string, boolean] =
	[1, "GeeksforGeeks", true];
const myArr3: [string, number] =
	[1, "GeeksforGeeks"];
const myArr4: [number, string, boolean] =
	[1, "GeeksforGeeks", true, 2];
console.log(myArr1);
console.log(myArr2);
console.log(myArr3);
console.log(myArr4);

Output:

["GeeksforGeeks", 1] 
[1, "GeeksforGeeks", true]
Type 'number' is not assignable to type 'string'.
Type 'string' is not assignable to type 'number'.
Type '[number, string, true, number]' is not assignable to type '[number, string, boolean]'.   
Source has 4 element(s) but target allows only 3.

Next Article

Similar Reads