Parameters
| Optional params | |
| Defaults | |
| Rest params | |
| Destructure params |
Optional params
A question mark after the name makes a parameter optional. Optional parameters hold the value undefined when the caller skips them. Keep required parameters first and optional ones last so calls stay readable.
function greet(name: string, title?: string): string {
if (title) {
return "Hello, " + title + " " + name;
}
return "Hello, " + name;
}
Defaults
A default value fills in the argument when the caller passes nothing or passes undefined. Defaults make common cases short while still allowing overrides. TypeScript reads the type from the default, so a separate annotation is rarely needed.
function greet(name: string = "guest"): string {
return "Hello, " + name;
}
const a: string = greet();
const b: string = greet("Ada");
Rest params
Rest parameters collect any number of trailing arguments into one typed array. The three dots gather the extras, and the array type says what each item must be. Use rest when the argument count is open ended.
function sum(...nums: number[]): number {
return nums.reduce((x, y) => x + y, 0);
}
Destructure params
Destructuring unpacks an object argument straight into named locals. Annotate the whole pattern once with an object type. Callers pass one clear options object instead of a long positional list.
function show({ name, age }: { name: string; age: number }): string {
return name + " is " + age;
}
Next: Overloads
Article author: Arthur Isaev