How to use Tuple Types In Typescript

Tuple types in TypeScript allow you to express an array with a fixed number of elements, where each element may be of a different type. By using tuple types, you can enforce a specific order and type for each element in the array.

Syntax:

type TupleType<T extends any[]> = T;

Example: In this example, we define a generic type TupleType for arrays with a fixed length and specific types for each element.

JavaScript
type TupleType<T extends any[]> = T;

const numbers: TupleType<number[]> = [1, 2, 3, 4];
const strings: TupleType<string[]> = ['Geeks', 'For', 'Geeks'];
const mixedArr: TupleType<(number | string | boolean)[]> =
    ['w3wiki', 1, 2, true, "TypeScript", false];

console.log("Numbers array: ", numbers);
console.log("Strings array: ", strings);
console.log("Mixed array: ", mixedArr);

Output:

"Numbers array: ",  [1, 2, 3, 4] 
"Strings array: ", ["Geeks", "For", "Geeks"]
"Mixed array: ", ["w3wiki", 1, 2, true, "TypeScript", false]


How to Define a Generic Type for an Array in TypeScript ?

Generics in TypeScript are a way to write reusable code that can work with different types of data. When it comes to defining generic types for arrays. TypeScript provides flexible options to ensure type safety while allowing for flexibility in the types of elements stored in the array.

Table of Content

  • Using the Type Alias
  • Using Array Generic Type
  • Using Tuple Types

Similar Reads

1. Using the Type Alias

The type alias can be used to define the generic type of the array and it can be used to type the array explicitly with the specified generic type....

2. Using Array Generic Type

TypeScript also provides a built-in generic type for arrays called Array. You can use it directly to define arrays with a specific element type....

3. Using Tuple Types

Tuple types in TypeScript allow you to express an array with a fixed number of elements, where each element may be of a different type. By using tuple types, you can enforce a specific order and type for each element in the array....