面试题答案
一键面试function combine<T extends string | number>(a: T, b: T): T extends string? string : number {
if (typeof a ==='string' && typeof b ==='string') {
return a + b as string;
} else if (typeof a === 'number' && typeof b === 'number') {
return a + b as number;
}
throw new Error('参数类型不匹配');
}
// 泛型在这种重载场景下的类型推导说明:
1. 定义泛型 `T`,约束它为 `string` 或 `number` 类型。
2. 当调用 `combine` 函数时,编译器会根据传入的实际参数类型来推导泛型 `T` 的具体类型。
3. 如果传入的两个参数都是 `string` 类型,那么 `T` 被推导为 `string`,函数返回拼接后的字符串。
4. 如果传入的两个参数都是 `number` 类型,那么 `T` 被推导为 `number`,函数返回相加后的数字。
5. 如果传入的参数类型不一致,函数会抛出错误,因为不符合定义的泛型约束。
上述代码以 TypeScript 实现,在其他支持泛型的语言(如 Java、C# 等)中,虽然语法略有不同,但思路类似。通过泛型的类型推导机制,可以在一定程度上简化这种重载场景的代码编写,同时保持类型安全。