← 返回课程: TypeScript from scratch

Optional, default, rest and overloads

视频即将上线

In the previous lesson we saw that TypeScript requires you to pass exactly the declared arguments. But many real functions are more flexible: a greeting with an optional title, a function with a default value, another that accepts a variable number of numbers. TypeScript has a syntax for each case. Today we learn four tools: optional parameters, default values, rest parameters and function overloads.

Optional and default parameters

Adding a question mark after the name makes the parameter optional. Inside the function, its type is the union with undefined, so strict forces you to check it before using it. Optional parameters must come at the end of the list. If instead of checking you prefer a fallback value, use a default value: the parameter becomes optional automatically and TypeScript infers its type from the value, so you do not have to annotate it.

typescript
function greet(name: string, title?: string): string {
  if (title === undefined) {
    return 'Hello, ' + name;
  }
  return 'Hello, ' + title + ' ' + name;
}

function power(base: number, exponent = 2): number {
  return base ** exponent; // exponent inferred as number
}

console.log(greet('Ana'));          // Hello, Ana
console.log(greet('Ana', 'Dr.'));   // Hello, Dr. Ana
console.log(power(5), power(2, 10)); // 25 1024

Rest parameters

A rest parameter gathers the remaining arguments into an array. It is written with three dots and its type is always an array, for example number[]. There can be only one and it must be last. It is the typed way to write functions like sum, which accept as many numbers as you like. In the call you can pass the values separately or spread an existing array with three dots.

typescript
function sum(...numbers: number[]): number {
  let total = 0;
  for (const n of numbers) {
    total += n;
  }
  return total;
}

const values = [4, 5, 6];
console.log(sum(1, 2, 3));   // 6
console.log(sum(...values)); // 15
console.log(sum());          // 0

Overloads

Sometimes the return type depends on the input type: if you pass a string you get a string, if you pass an array you get an array. A union on the parameter does not express this well, because the result would always be the union of both possibilities. Overloads solve this: you write several signatures, each with its input and output, and then a single implementation that must be compatible with all of them. Callers only see the signatures, not the implementation. Use them sparingly: if a union or a generic is enough, they are simpler.

typescript
function firstItem(value: string): string;
function firstItem<T>(value: T[]): T | undefined;
function firstItem(value: string | unknown[]): unknown {
  return value[0];
}

const letter = firstItem('hello');   // type: string
const num = firstItem([10, 20, 30]); // type: number | undefined
console.log(letter, num);
// firstItem(42); // error: No overload matches this call

An alternative to long lists of optional parameters is receiving a single options object. Instead of formatPrice(12, 'EUR', 2, true), you write formatPrice(12, { currency: 'EUR', decimals: 2 }) with an object type whose properties are optional. That way the order does not matter, each call reads on its own and adding a new option breaks nobody. Combine it with default values through destructuring in the parameter, and you will have functions that are comfortable to use and easy to extend. It is one of the most common practices in TypeScript libraries.

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →