TypeScript ยท Chapter 19 of 44

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.

Syntax
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.

Example 1 (typescript)
function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}
console.log(greet("Sam"));
console.log(greet("Sam", "Hi"));
Output
Hello, Sam!
Hi, Sam!

greeting has a default value used when the caller doesn't provide one.

Example 2 (typescript)
function describe(name: string, age?: number): string {
  if (age !== undefined) {
    return `${name} is ${age}`;
  }
  return `${name}'s age is unknown`;
}
console.log(describe("Kai"));
Output
Kai's age is unknown

age 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.
๐Ÿ’ก Note: Optional parameters must come after required parameters in the parameter list.

๐Ÿ“ Quick Quiz

1. How do you mark a function parameter as optional?

2. What happens when a parameter has a default value and the caller omits it?

3. Where must optional parameters appear in the parameter list?