技术文档中心
首页
React
Vue
TypeScript
Kotlin
React Native
Electron
Android
首页
React
Vue
TypeScript
Kotlin
React Native
Electron
Android
  • 基础入门

    • TypeScript 学习指南
    • 基础类型
    • 函数
    • 接口
    • 类
  • 进阶内容

    • 泛型
    • 高级类型
    • 工具类型
    • 装饰器
    • 模块
  • 实战应用

    • 配置文件
    • 实战应用

函数

函数类型

函数声明

function add(x: number, y: number): number {
  return x + y;
}

函数表达式

let add: (x: number, y: number) => number = function(x, y) {
  return x + y;
};

// 完整写法
let add: (x: number, y: number) => number = function(x: number, y: number): number {
  return x + y;
};

箭头函数

let add = (x: number, y: number): number => x + y;

可选参数

function buildName(firstName: string, lastName?: string): string {
  if (lastName) {
    return `${firstName} ${lastName}`;
  }
  return firstName;
}

buildName('John');
buildName('John', 'Doe');

默认参数

function buildName(firstName: string, lastName = 'Doe'): string {
  return `${firstName} ${lastName}`;
}

buildName('John');        // 'John Doe'
buildName('John', 'Smith'); // 'John Smith'

剩余参数

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

sum(1, 2, 3, 4, 5); // 15

函数重载

// 重载签名
function reverse(x: string): string;
function reverse(x: number): number;

// 实现签名
function reverse(x: string | number): string | number {
  if (typeof x === 'string') {
    return x.split('').reverse().join('');
  }
  return Number(x.toString().split('').reverse().join(''));
}

reverse('hello'); // 'olleh'
reverse(12345);   // 54321

this 参数

interface User {
  name: string;
  greet(this: User): void;
}

let user: User = {
  name: 'John',
  greet() {
    console.log(`Hello, ${this.name}`);
  }
};

user.greet(); // 正确
let greet = user.greet;
// greet(); // 错误

泛型函数

function identity<T>(arg: T): T {
  return arg;
}

identity<string>('hello');
identity<number>(123);
identity(true); // 自动推断

回调函数

function fetchData(callback: (data: string) => void): void {
  setTimeout(() => {
    callback('data');
  }, 1000);
}

fetchData((data) => {
  console.log(data);
});

函数类型别名

type MathFunc = (x: number, y: number) => number;

let add: MathFunc = (x, y) => x + y;
let subtract: MathFunc = (x, y) => x - y;

构造函数

interface ClockConstructor {
  new (hour: number, minute: number): ClockInterface;
}

interface ClockInterface {
  tick(): void;
}

function createClock(
  ctor: ClockConstructor,
  hour: number,
  minute: number
): ClockInterface {
  return new ctor(hour, minute);
}
最近更新: 2026/2/6 15:39
Contributors: hailong
Prev
基础类型
Next
接口