📝 基本语法
// 泛型默认类型:使用 = 指定
interface ApiResponse<T = unknown> {
data: T;
status: number;
message: string;
}
// 不指定类型时使用默认类型
const response1: ApiResponse = {
data: 'any data',
status: 200,
message: 'OK'
};
// 指定类型时覆盖默认类型
const response2: ApiResponse<User> = {
data: { id: 1, name: 'Alice' },
status: 200,
message: 'OK'
};
interface User {
id: number;
name: string;
}
🔧 多个默认类型
// 多个泛型参数的默认类型
interface ApiRequest<T = unknown, U = Record<string, unknown>> {
body: T;
headers: U;
}
// 使用所有默认类型
const request1: ApiRequest = {
body: 'data',
headers: {}
};
// 覆盖第一个,使用第二个默认
const request2: ApiRequest<string> = {
body: 'data',
headers: { 'Content-Type': 'application/json' }
};
// 覆盖所有默认类型
const request3: ApiRequest<User, { Authorization: string }> = {
body: { id: 1, name: 'Alice' },
headers: { Authorization: 'Bearer token' }
};
💡
默认类型规则
有默认类型的泛型参数可以不指定;没有默认类型的必须指定。默认类型参数应放在参数列表末尾。