Lesson 7 / 26
Typed Function Parameters
Type parameters and return values, and make some optional.
Params & return type
Annotate each parameter, and optionally the return type after ).
function area(width: number, height: number): number {
return width * height;
}
area(4, 5); // 20Optional & default params
? marks a parameter optional; a default value makes it optional too and sets its type from that value.
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
function findUser(id: number, cache?: Map<number, string>) { /* ... */ }Calling it wrong
Wrong argument count or type is rejected before the code ever runs.
area(4);
// Error: Expected 2 arguments, but got 1.
area(4, "5");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.Quick check: Which makes a function parameter optional?
- A trailing `?` after its name
- Wrapping it in `unknown`
- Putting it first in the parameter list
Answer
A trailing `?` after its name — `name?: string` tells TS the caller may omit this argument.