How to use Union Types In Typescript
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.
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).
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