🎯 学习目标

  • 掌握泛型接口的定义语法
  • 理解泛型接口的两种形式
  • 学会在接口中使用泛型约束
  • 了解泛型接口的实际应用

📝 泛型接口定义

// 泛型接口 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> 放在方法签名中:每次调用可以不同类型。

📝 本节小结

  • • 接口名后加 <T> 定义泛型接口
  • • 泛型参数在整个接口内可用
  • • 常用于 API 响应、容器类型
  • • 可与函数签名泛型组合使用