TypeScript Functions
TypeScript lets you annotate function parameters and return types, ensuring both the inputs and outputs of a function match expected types. This catches many bugs caused by passing the wrong kind of argument.
You can also mark parameters as optional with `?`, or give them default values, both of which affect whether the caller is required to supply that argument.
function add(a: number, b: number): number {
return a + b;
}Typed parameters and return values
You annotate each parameter with `: type` and the return value after the parameter list, like `function add(a: number, b: number): number { ... }`.
Optional and default parameters
A parameter marked with `?`, like `greeting?: string`, becomes optional. A parameter with a default value, like `greeting: string = "Hi"`, is used automatically when the caller omits it.
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greet("Sam"));
console.log(greet("Sam", "Hi"));Hello, Sam!
Hi, Sam!greeting has a default value used when the caller doesn't provide one.
function describe(name: string, age?: number): string {
if (age !== undefined) {
return `${name} is ${age}`;
}
return `${name}'s age is unknown`;
}
console.log(describe("Kai"));Kai's age is unknownage is optional, so the function can be called without it.
Key points
- Function parameters and return values can both be annotated with types.
- A `?` after a parameter name makes it optional.
- Default values are used automatically when an argument is omitted.
- TypeScript checks argument types match at every call site.
