首页/文档/泛型

泛型

创建可复用的组件

进阶

概述

泛型是TypeScript中用于创建可复用组件的特性。它允许你编写可以处理多种类型的代码,而不是只处理一种类型。

泛型可以用于函数、接口、类等。

泛型函数

typescript
加载中...

泛型接口和类

泛型接口和类

泛型接口:

interface Box<T> {
  value: T;
}

const numberBox: Box<number> = { value: 42 };
const stringBox: Box<string> = { value: "hello" };

泛型类:

class Container<T> {
  private value: T;

  constructor(value: T) {
    this.value = value;
  }

  getValue(): T {
    return this.value;
  }
}

泛型约束

typescript
加载中...

泛型工具类型

typescript
加载中...