Typescript中的泛型
可以把泛型想象成 "类型的变量":
1.定义时,用<T>声明一个类型变量(T 是约定的名称,也可以用其他字母)
2.使用时,指定具体类型,如identity<string>("hello")
3.TypeScript 通常能自动推断类型,所以也可以简写为identity("hello")
泛型的应用场景
一、函数泛型:
function getFirstElement<T>(array: T[]): T { return array[0]; } // 使用时可以指定类型,也可以让TS自动推断 const num = getFirstElement<number>([1, 2, 3]); // number类型 const str = getFirstElement(["a", "b", "c"]); // string类型
二、接口泛型:
interface Box<T> { value: T; } const numberBox: Box<number> = { value: 10 }; const stringBox: Box<string> = { value: "hello" };
三、类泛型:
class Container<T> { private value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } } const numberContainer = new Container(100); const stringContainer = new Container("test");

浙公网安备 33010602011771号