Tuple types are used to model arrays of specific lengths and element types in typescript.
// first tuple stores the number
let arrayA: [ number, number] = [ 10, 20];
// tuple stores a value that string, number and boolean
let arrayB: [ string, number, boolean ] = [ “hello”, 10, 20 ];
Tuples are more sophisticated in the typescript, as they are also using to model things like parameter lists in JavaScript. Tuples can have the rest elements and optional elements and can have the labels for readability.
// A tuple that has either one or two strings.
let a: [string, string?] = ["abc"];
a = ["abc", "xyz"];
// A labeled tuple that has either one or two strings.
let b: [first: string, second?: string] = ["hello"];
b = ["hello", "world"];
// A tuple with a *rest element* - holds at least 2 strings at the front,
// and any number of booleans at the back.
let c: [ string, string, ...boolean[] ];
c = [ "hello", "world" ];
c = [ "hello", "world", false ];
c = [ "hello", "world", true, false, true ];
The rest elements have been specially developed so that they can be used in typescript 4.2.Typescript allowed the rest element in the last position of a tuple type in the previous versions. But in this version, the rest elements can occur at any position in the tuple with few restrictions.
let a: [ ...string[], number ];
a = [ 100 ];
a = [ "Keval", 200 ];
a = [ "Keval", "Maulik", "Krishna", 300 ];
let b: [ boolean, ...string[], number ];
b = [ true, 100 ];
b = [ false, "Keval", 200 ];
b = [ true, "Keval", "Aniket", "Dhruv", 300 ];
The only limitation is that a rest element can be placed anywhere in a tuple unless it is not followed by another rest element or an optional element. We can write only one rest element in a tuple.
let b: [ ...number[], boolean, ...string[] ]; // rest element can not follow another rest element
let d: [ ...number[], string? ];
// optional element can not follow a rest element