When using the destructuring assignment syntax in JavaScript, you can capture all remaining items in an array with the "rest" pattern in the following way:
const [ head, ...rest ] = [1, 2, 3, 4]; console.log(head); // output: 1 console.log(rest); // output: [2, 3, 4]
In such cases, to properly type the rest parameters, you can use the following methods:
Add Type for Array Elements Having the Same Type
If the type of all elements in the array is the same, then we can simply add a common type like so:
const [ head, ...rest ]: number[] = [1, 2, 3, 4];
Add Types for Array Elements Having Different Types
To apply different types to different elements in an array, we can use tuples like so:
const [ head, ...rest ]: [string, ...number[]] = ['a', 2, 3, 4];
In the case above, the first destructured element will have the type string
and the remaining elements will have the type number
.
Now, let's consider the following array where we have a mix of different types of elements in an array:
const [ head, ...rest ]: [string, number, number, ...string[]] = ['a', 2, 3, 'b', 'c'];
This would translate to something like the following:
head: string; rest[0]: number; rest[1]: number; rest[2]: string, ...
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.