How do you give a function parameter a default value, and how does TypeScript infer its type?
Short answer
Assign a default value directly in the parameter list using '='; TypeScript infers the parameter's type from the default value's type unless you also add an explicit annotation, and the parameter becomes optional to callers.
Advertisement
AModel answer
Assign a default value directly in the parameter list using '='; TypeScript infers the parameter's type from the default value's type unless you also add an explicit annotation, and the parameter becomes optional to callers.
function greet(name: string, greeting = 'Hello') {
return `${greeting}, ${name}`;
}
greet('Sam'); // 'Hello, Sam'
greet('Sam', 'Hi'); // 'Hi, Sam'Real-world example
Providing a sensible default page size or sort order for a paginated query function.
Likely follow-ups
- Can a default parameter's value reference an earlier parameter in the same function?
Related topics