Open In App

Defining array with multiple types in TypeScript

Last Updated : 11 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
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 formed by defining more than one explicit data type separated using the vertical straight line (|) inside the round braces and then using that union to explicitly type the array. This method can be used to create an array with n number of elements of different data types at random indexes.

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads