How to Create an Array of Multiple Data Types in TypeScript ?
Last Updated :
12 Feb, 2024
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.
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"]
Share your thoughts in the comments
Please Login to comment...