但实际上 TypeScript 不仅函数有泛型,类型(Type)和接口(Interface)也可以有泛型。
这就是 TypeScript 的泛型(Generics)。
1. 函数泛型
这是你已经熟悉的用法:
function test<T>(value: T): T {
return value;
}
test<string>("hello");
test<number>(123);
这里的 <T> 是泛型参数,调用函数时可以指定具体类型。
2. 接口泛型(Interface Generics)
接口也可以定义泛型:
interface Box<T> {
value: T;
}
使用时:
const box1: Box<string> = {
value: "hello"
};
const box2: Box<number> = {
value: 123
};
这里:
Box<T>:定义了一个带泛型参数的接口。Box<string>:表示 value 必须是 string 类型。Box<number>:表示 value 必须是 number 类型。
3. 类型别名泛型(Type Generics)
使用 type 定义的类型同样可以有泛型:
type Result<T> = {
data: T;
success: boolean;
};
使用:
const result: Result<string> = {
data: "成功",
success: true
};
4. 回到 React 的 ChangeEvent
现在再看:
ChangeEvent<HTMLInputElement>
你就容易理解了。
React 内部实际上定义了类似这样的接口:
interface ChangeEvent<T = Element> extends SyntheticEvent<T> {
target: EventTarget & T;
}
这是简化后的结构,用来帮助理解。
其中:
ChangeEvent<T>:一个带泛型参数的接口。T = Element:默认泛型参数是 Element。HTMLInputElement:调用时传入的具体类型。
因此:
ChangeEvent<HTMLInputElement>
就是将 T 替换为 HTMLInputElement。
5. 总结:TypeScript 哪些地方可以使用泛型?
| 类型 | 是否支持泛型 | 示例 |
|---|
| 函数 | 支持 | function test<T>() |
| 接口 interface | 支持 | interface Box<T> |
| 类型别名 type | 支持 | type Box<T> = ... |
| 类 class | 支持 | class Box<T> |
最重要的理解:
泛型并不是函数专属的功能,而是一种可以应用于函数、接口、类型别名和类的类型设计机制。
它的核心思想是:先定义一个通用的类型模板,使用时再传入具体类型。