TypeScript supports precise typing of functions using rest parameters and destructuring. This is particularly important for functions that accept a variable number of arguments or complex objects.
Destructuring in function parameters allows you to explicitly define the structure of expected properties:
function printUser({ name, age }: { name: string; age: number }) { console.log(`${name} (${age})`); }
Rest parameters allow you to define a variable number of arguments and their type:
function sum(...numbers: number[]): number { return numbers.reduce((acc, cur) => acc + cur, 0); }
The combined use occurs in functions that accept a main object and an additional array of parameters:
function logEvent(event: { type: string }, ...meta: any[]) { console.log(event.type, meta.join(',')); }
Correct typing allows errors to be identified before code execution, but incorrect typing will lead to a loss of type safety and runtime errors.
How to specify a type for a function with destructured default parameters and make them optional?
Many specify the type of the object but forget to make each field optional or to set default values simultaneously with the type:
function foo({x = 1, y = 2}: {x?: number; y?: number} = {}) { console.log(x, y); }
Here, default values are set, and all parameters are made optional with the ?. Without this, a call without parameters will cause an error, although a default is expected.
Story
undefined has no property name.Story
any[], which allowed not only numbers to be passed. In production, numbers and strings were unexpectedly summed, resulting in incorrect figures in reports.Story
Destructuring was used with a deeply nested object, but nested types were not specified. As a result, TS "got lost" and did not indicate the absence of a required field in objects, leading to the TypeError: Cannot read property 'id' of undefined error on the client side.