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

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

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

    • 配置文件
    • 实战应用

高级类型

联合类型

let value: string | number;
value = 'hello';
value = 123;

function print(id: string | number) {
  console.log(id);
}

交叉类型

interface Person {
  name: string;
}

interface Employee {
  id: number;
}

type Staff = Person & Employee;

let staff: Staff = {
  name: 'John',
  id: 1001
};

类型守卫

typeof

function print(value: string | number) {
  if (typeof value === 'string') {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }
}

instanceof

class Dog {
  bark() {
    console.log('汪汪');
  }
}

class Cat {
  meow() {
    console.log('喵喵');
  }
}

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark();
  } else {
    animal.meow();
  }
}

in

interface Bird {
  fly(): void;
}

interface Fish {
  swim(): void;
}

function move(animal: Bird | Fish) {
  if ('fly' in animal) {
    animal.fly();
  } else {
    animal.swim();
  }
}

自定义类型守卫

interface Bird {
  fly(): void;
}

interface Fish {
  swim(): void;
}

function isBird(animal: Bird | Fish): animal is Bird {
  return (animal as Bird).fly !== undefined;
}

function move(animal: Bird | Fish) {
  if (isBird(animal)) {
    animal.fly();
  } else {
    animal.swim();
  }
}

可辨识联合

interface Square {
  kind: 'square';
  size: number;
}

interface Rectangle {
  kind: 'rectangle';
  width: number;
  height: number;
}

interface Circle {
  kind: 'circle';
  radius: number;
}

type Shape = Square | Rectangle | Circle;

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'square':
      return shape.size * shape.size;
    case 'rectangle':
      return shape.width * shape.height;
    case 'circle':
      return Math.PI * shape.radius ** 2;
  }
}

索引类型

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

let user = {
  name: 'John',
  age: 25
};

let name = getProperty(user, 'name'); // string
let age = getProperty(user, 'age');   // number

映射类型

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

type Partial<T> = {
  [P in keyof T]?: T[P];
};

interface User {
  name: string;
  age: number;
}

type ReadonlyUser = Readonly<User>;
type PartialUser = Partial<User>;

条件类型

T extends U ? X : Y

// 示例
type IsString<T> = T extends string ? true : false;

type A = IsString<string>;  // true
type B = IsString<number>;  // false

infer

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

function getUser() {
  return { name: 'John', age: 25 };
}

type User = ReturnType<typeof getUser>; // { name: string; age: number }

模板字面量类型

type World = 'world';
type Greeting = `hello ${World}`; // 'hello world'

type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<'click'>; // 'onClick'

// 组合
type Direction = 'left' | 'right' | 'top' | 'bottom';
type Margin = `margin${Capitalize<Direction>}`;
// 'marginLeft' | 'marginRight' | 'marginTop' | 'marginBottom'

类型别名

type ID = string | number;

type User = {
  id: ID;
  name: string;
  age: number;
};

type Callback = (data: string) => void;

类型断言

// as
let value: unknown = 'hello';
let length = (value as string).length;

// 非空断言
let name: string | null = getName();
let upper = name!.toUpperCase();

// 常量断言
let obj = { name: 'John' } as const;
// obj.name = 'Jane'; // 错误

类型推断

// 自动推断
let num = 123; // number
let str = 'hello'; // string

// 最佳通用类型
let arr = [1, 2, 3]; // number[]
let mixed = [1, 'hello']; // (string | number)[]

// 上下文类型
window.onmousedown = function(event) {
  // event 推断为 MouseEvent
};
最近更新: 2026/2/6 15:39
Contributors: hailong
Prev
泛型
Next
工具类型