Skip to content

输入函数 in TypeScript

类型函数参数, 返回值, 可选 and REST params, and 函数 overloads.

你将学到

  • 如何 annotate 函数参数 and 返回类型
  • 可选, 默认, and REST 参数
  • Using 函数类型 signatures and 回调
  • 函数 overloads for 多个 call signatures

概念讲解

Parameter and Return Types

每个function parameter can have a type annotation, and the return type follows the parameter list: 函数 添加(: 数字, b: 数字): 数字. Return type annotations are optional (TypeScript infers them) but recommended for public APIs because they catch accidental return-type changes during refactoring. A function with no return value has type 空.

Optional, Default, and Rest Parameters

Optional parameters use a question mark (name?: 字符串) and must come after required parameters. Default parameters (name: 字符串 = "Anonymous") are automatically optional. Rest parameters collect remaining arguments into an array: 函数 总和(...nums: 数字[]): 数字. These three features let you define flexible function signatures that accept varying inputs.

Function Overloads

Some functions behave differently for different parameter types — for example, 格式(date: Date): 字符串 and 格式(timestamp: 数字): 字符串. Function overloads let you declare multiple signatures for a single implementation. You write the overload signatures first, then a general implementation signature. Callers see the specific overloads with precise types, while the implementation handles all cases internally.

示例代码

              // Basic function with typed params and return.
function add(a: number, b: number): number {
  return a + b;
}

// Optional, default, and rest parameters.
function greet(name: string, title?: string, ...tags: string[]): string {
  const t = title ?? "Friend";
  return `Hello ${t} ${name} [${tags.join(", ")}]`;
}

// Function type signature for callbacks.
type Comparator<T> = (a: T, b: T) => number;
const numCompare: Comparator<number> = (a, b) => a - b;

// Function overloads — multiple call signatures.
function format(input: Date): string;
function format(input: number): string;
function format(input: Date | number): string {
  return new Date(input).toISOString();
}

console.log(add(1, 2));
console.log(greet("Alice", "Dr.", "vip", "new"));
console.log(format(1700000000000));
            

Annotate 参数 and 返回类型. Use ? for 可选, = for defaults, ... for REST. Overloads declare 多个精确 signatures for one implementation.

动手试一试

  • Regex Tester

    类型-safe 函数经常 wrap regex logic — 测试模式这里.

  • Code Diff

    Compare overloaded and 非-overloaded 函数 implementations.

常见错误

错误写法

Putting 可选参数之前必需 ones

正确做法

必需参数必须 come 首先. 可选 (?) and 默认参数必须 come 之后所有必需参数 in 函数 signature.

错误写法

编写 overloads 不使用 compatible implementation signature

正确做法

implementation signature 必须是 compatible 使用所有 overload signatures. 列表 overloads 首先, 然后 implementation 使用通用 (通常 union) signature.

练习 输入函数 in TypeScript

7 个练习

练习 输入函数 in TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误