Destructured And Rest Parameters
Rest parameters — "the remaining arguments as an array"
...name collects any number of trailing arguments into an array. You type it as an array type.
function restParameters(a: string, b: number, ...c: string[]) {
console.log(a, b, c); // c = ['string', 'string', 'ajay']
}
restParameters("asd", 3, "string", "string", "ajay");
function sum(...nums: number[]) {
return nums.reduce((prev, curr) => prev + curr, 0);
}
sum(1, 2, 44); // 47
Destructured parameters — type the whole object
When a function takes a destructured object, the type annotation describes the object being destructured, not each variable:
function greet({ first, second }: { first: string; second: number }) {
console.log(first, second);
}
greet({ first: "Ajay", second: 34 });
Both together — ...rest always comes last
You can destructure some properties by name and collect the rest:
function desRest({ a, b, ...rest }: {
a: number;
b: string;
c: string[];
d: number[];
}) {
console.log(a, b, rest); // rest = { c: [...], d: [...] }
}
desRest({ a: 2, b: "ajay", c: ["ad", "ad"], d: [2, 343] });
...rest must always be at the end
A rest element collects "everything left over," so nothing can follow it — in both array rest params and object destructuring.
function f(...nums: number[], last: string) {} // Error: rest must be last
The rule is the same everywhere rest appears: it swallows the remainder, so it can only sit in the final position.