在 TypeScript 中,extends

发布时间 2023-11-14 11:16:38作者: Tsunami黄嵩粟

extends 是一个关键字,用于指定类型参数的约束。它在类型参数的声明中使用,以确保类型参数满足特定的条件。

具体来说,extends 后面可以跟随一个类型,表示类型参数必须是该类型的子类型。在泛型类型或泛型函数中,这样的约束可以提供更强的类型安全性,使得类型参数符合特定的要求。

以下是一些示例说明 extends 的用法:

泛型类型的基本用法:

type MyType<T extends number> = {
  value: T;
};

const example: MyType<number> = {
  value: 42
};

在这个例子中,T extends number 表示 T 必须是 number 类型或其子类型。

多重约束:

type MyType<T extends number | string> = {
  value: T;
};

const example1: MyType<number> = {
  value: 42
};

const example2: MyType<string> = {
  value: 'hello'
};

在这个例子中,T extends number | string 表示 T 必须是 numberstring 类型或其子类型。

通过接口进行约束

interface MyInterface {
  length: number;
}

type MyType<T extends MyInterface> = {
  data: T;
};

const example: MyType<string> = {
  data: 'hello' // Error: 'string' does not satisfy the constraint 'MyInterface'
};

const validExample: MyType<{ length: number }> = {
  data: { length: 5 }
};
  1. 在这个例子中,T extends MyInterface 表示 T 必须是实现了 MyInterface 接口的类型。

总的来说,extends 关键字用于对类型参数进行约束,确保其符合特定的条件,从而提高 TypeScript 代码的类型安全性。