Open In App

How to Create an Array of Multiple Data Types in TypeScript ?

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, you can not directly define an array as you usually define it in JavaScript. You need to explicitly type the array with a particular data type whose values can be stored inside it. The type of an array can be specified using the colon syntax followed by the data type (:type). You can also create arrays that can store values of multiple data types using the Union type to explicitly type the array.

Using Union Types

This approach involves explicitly specifying a union type for the array, allowing it to store values of multiple types.

Example: The below code will illustrate how you can create an array that stores values of multiple data types in TypeScript.

Javascript
const singleTypeArr: string[] = [
    "GFG",
    "TypeScript",
];

const multiTypeArr: (
    | number
    | string
    | boolean
)[] = [12, "GFG", true, "TypeScript"];

console.log(singleTypeArr);
console.log(multiTypeArr);

Output:

["GFG", "TypeScript"]
[12, "GFG", true, "TypeScript"]

singleTypeArr is a TypeScript array explicitly typed to contain only strings. multiTypeArr is an array that can store values of type number, string, or boolean, defined using Union Types (number | string | boolean).

Using Type Assertion

Another approach is to use type assertion to create arrays of multiple data types.

Example: This TypeScript code initializes `mixedArr` without specifying type but later asserts it to accept numbers, strings, or booleans using (number | string | boolean)[]. It then logs the array.

JavaScript
const mixedArr = [12, "GFG", true, "TypeScript"] as (number | string | boolean)[];

console.log(mixedArr); 

Output:

[12, "GFG", true, "TypeScript"]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads