Defining array with multiple types in TypeScript
Last Updated :
23 Jul, 2024
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 created by defining multiple explicit data types separated by a vertical bar (|) inside parentheses. This union type is then used to explicitly type the array, allowing it to hold elements of any of the specified types at any index.
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.
Similar Reads
TypeScript Defining a Union Type In this article, we are going to learn about Defining a Union Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a union type allows a variable to have one of several possible types. You can define a union type by using
3 min read
What are template literal types in Typescript ? Template literal types in TypeScript allow the construction of new string literal types by combining existing string literal types using template literal syntax.They enable the creation of complex string patterns by embedding unions and other literal types within template literals.This feature enhan
3 min read
What are intersection types in Typescript ? In Typescript, Although intersection and union types are similar, they are employed in completely different ways. An intersection type is a type that merges several kinds into one. This allows you to combine many types to create a single type with all of the properties that you require. An object of
3 min read
TypeScript Creating Types from Utility Type TypeScript Creating Types from Utility Type increases the code readability and ease of use when using any complex operations and values, there are different ways to do the type creation with the existing ones. TypeScript Creating Types from Utility Type:Generics: It basically allows us to declare th
3 min read
What is Type Erasure in TypeScript? TypeScript is a very mighty superset of JavaScript, which adds static typing to the language and allows developers to catch errors early on as well as write more maintainable code. This being said a TypeScript type system erases type information at compile time (or during the compilation), a phenome
4 min read
What are string literal types in TypeScript ? The string literal type was added in TypeScript version 1.8. String literal types work well with union types and type aliases in practice. These properties can be combined to give strings enum-like functionality. The string literal type allows you to specify a set of possible string values for a var
3 min read
What are Hybrid Types in TypeScript? Hybrid types are used by TypeScript to refer to types that combine different things such as objects, functions, arrays etc. In this article, we will learn more about Hybrid Types in TypeScript.What are Hybrid Types in TypeScript?In TypeScript, using interfaces or type aliases we can define hybrid ty
2 min read
Typescript Generic Type Array A generic type array is an array that is defined using the generic type in TypeScript. A generic type can be defined between the angled brackets(<>). Syntax:// Syntax for generic type arraylet myArray: Array<Type>;Example 1: Creating a simple generic type array of number type in Typescri
1 min read
What is Type Annotations in TypeScript ? TypeScript Type Annotations allow developers to explicitly define the types of variables, functions, and other elements in the program.They help catch mistakes early by ensuring the right data type is used.They make the code easier to understand and follow.Type Annotations help avoid errors and make
3 min read