📝 泛型接口定义
// 泛型接口
interface Container<T> {
value: T;
getValue(): T;
setValue(value: T): void;
}
const numberContainer: Container<number> = {
value: 123,
getValue() { return this.value; },
setValue(value) { this.value = value; }
};
// API 响应接口
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
interface User {
id: number;
name: string;
}
const response: ApiResponse<User> = {
data: { id: 1, name: 'Alice' },
status: 200,
message: 'Success'
};
🔧 泛型函数接口
// 泛型函数类型接口
interface GenericFunction {
<T>(arg: T): T;
}
const identity: GenericFunction = (arg) => arg;
// 与泛型参数在接口上的区别
interface GenericFunction2<T> {
(arg: T): T;
}
const identityNumber: GenericFunction2<number> = (arg) => arg;
const identityString: GenericFunction2<string> = (arg) => arg;
💡
两种泛型接口
<T> 放在接口名后:整个接口使用同一类型;<T> 放在方法签名中:每次调用可以不同类型。