Generics in Typescript

· 207 words · 1 minute read

Tuples is a type that exists in Typescript which is similar to Array type but has fixed length and defined what kind of element (either same or different types) will be there at a certain position.

// Array example
const a: number[] = [1, 2, 3];

// Tuple example
const t: [string, number, boolean] = ["2", 1, true];

Since Tuples are just arrays, so it will allow to push a new element only of type either string or number as defined in the tupleType below. But if we try to access the element at that index, it will give an error message.

type tupleType = [string, number];

const t: tupleType = ["hello", 1];

// Inserting any other type except string or number will result in error
t.push(2);

console.log(t[0]); // hello

console.log(t[1]); // 1

// Tuple type 'tupleType' of length '2' has no element at index '2'.
console.log(t[2]);

Tuples can also have an optional value which comes at the end. Optional properties can be defined by using ? (question symbol) after the property type.

type tupleType = [string, number, boolean?];

const t: tupleType = ["hello", 1];

/* If you mouse over the length below 
  it states that length can be either 2 | 3
  */
console.log(t.length); // 2