Destructuring assignment and rest parameters are awesome and typical in codebases these days. Is it possible to strongly-type these though in TypeScript? Let’s find out.

TypeScript has tuples

Before we figure out how to strongly-type rest parameters, let’s understand tuples. A tuple can be thought of as an array with a fixed number of elements. They are nice for small and obvious data structures. For example, the useState React hook returns a tuple:

const [state, setState] = useState(initialState);

TypeScript lets us define tuples in a type annotation by specifying the type of each element in square brackets. For example:

const tomScore: [string, number]: ["Tom", 70];

Open-ended tuples

What have tuples got to do with rest parameters? Well, we’ll get there eventually.

TypeScript lets us have tuples where we can have a varying number of end elements like below:

["Tom", 70][("Jane", 70, 60)][("Fred", 70, 60, 80)];

We can specify the type for the above example as [string, ...number[]].

#typescript #rest

Strongly-typed Destructuring and Rest Parameters
1.40 GEEK