How to use Type Assertion In Typescript

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"]

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

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.

Table of Content

  • Using Union Types
  • Using Type Assertion

Similar Reads

Using Union Types

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

Using Type Assertion

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