全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-21 6 分钟 ✍️ juanwangdev

TypeScript 函数类型

函数是 TypeScript 的核心类型,下面梳理参数与返回值的类型标注方式。

参数类型

TypeScript
function greet(name: string, age: number): string {
  return `Hello ${name}, you are ${age} years old.`;
}

// 箭头函数
const add = (a: number, b: number): number => a + b;

可选参数

使用 ? 标记可选:

TypeScript
function buildUrl(host: string, port?: number): string {
  if (port) {
    return `http://${host}:${port}`;
  }
  return `http://${host}`;
}

buildUrl("localhost");        // ✅
buildUrl("localhost", 8080);  // ✅

注意:可选参数必须在必选参数之后。

默认参数

TypeScript
function createConnection(host: string, port: number = 80): string {
  return `${host}:${port}`;
}

createConnection("localhost");  // port 默认为 80

剩余参数

TypeScript
function sum(...numbers: number[]): number {
  return numbers.reduce((acc, n) => acc + n, 0);
}

sum(1, 2, 3);  // 6

返回值类型

显式标注

TypeScript
function parseJSON(str: string): object {
  return JSON.parse(str);
}

void 返回

TypeScript
function log(msg: string): void {
  console.log(msg);
}

never 返回

TypeScript
function throwError(msg: string): never {
  throw new Error(msg);
}

function loop(): never {
  while (true) {}
}

函数类型表达式

TypeScript
type MathFn = (a: number, b: number) => number;

const multiply: MathFn = (a, b) => a * b;
const divide: MathFn = (a, b) => a / b;

函数重载

同一函数名,不同参数签名:

TypeScript
function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals: number = 2): string {
  if (typeof value === "string") {
    return value.trim();
  }
  return value.toFixed(decimals);
}

format("  hello ");  // "hello"
format(3.14159);     // "3.14"
format(3.14159, 3);  // "3.142"

注意:重载签名必须具体,实现签名必须兼容所有重载签名。

回调函数类型

TypeScript
function fetchData(url: string, callback: (error: Error | null, data?: string) => void): void {
  // 模拟异步
  callback(null, "data");
}

fetchData("/api", (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});

要点总结

  • 参数类型直接标注,可选参数用 ?,默认参数用 =
  • 返回值类型可省略让编译器推断,但复杂函数建议显式标注
  • void 表示无返回值,never 表示永不返回(异常/死循环)
  • 函数重载需先声明签名再写实现,实现签名必须兼容所有重载
  • 回调函数参数需标注参数类型与返回值类型

📝 发现内容有误?点击此处直接编辑

下一篇 → TypeScript 基础类型与枚举
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库