MST
星途 面试题库

面试题:TypeScript 泛型中类型兼容性与类型推断的微妙关系

在 TypeScript 泛型编程中,定义一个泛型函数 `fn<T extends { prop: string }>(arg: T): { newProp: T['prop'] }`,现在有两个类型 `type SubType1 = { prop: string; other: number }` 和 `type SubType2 = { prop: string; anotherProp: boolean }`。分析当分别传入 `SubType1` 和 `SubType2` 类型参数时,类型兼容性和类型推断在泛型函数中的具体行为,并且解释如果希望函数对这两种类型都能正确工作,需要在类型定义上做哪些调整。
16.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 类型兼容性和类型推断行为分析
    • 传入 SubType1 类型参数
      • SubType1 满足 T extends { prop: string } 的约束,因为 SubType1prop 属性且类型为 string
      • 类型推断会将 T 推断为 SubType1,函数返回类型为 { newProp: SubType1['prop'] },也就是 { newProp: string }
    • 传入 SubType2 类型参数
      • SubType2 同样满足 T extends { prop: string } 的约束,因为它也有 prop 属性且类型为 string
      • 类型推断会将 T 推断为 SubType2,函数返回类型为 { newProp: SubType2['prop'] },也就是 { newProp: string }
  2. 类型定义调整
    • 当前函数定义已经可以对这两种类型正确工作,无需调整。因为泛型约束 T extends { prop: string } 只关心 prop 属性及其类型,而 SubType1SubType2 都满足这个约束。函数返回类型只依赖于 prop 属性,所以不需要额外调整类型定义。
function fn<T extends { prop: string }>(arg: T): { newProp: T['prop'] } {
    return { newProp: arg.prop };
}

type SubType1 = { prop: string; other: number };
type SubType2 = { prop: string; anotherProp: boolean };

const result1 = fn<SubType1>({ prop: 'test', other: 1 });
const result2 = fn<SubType2>({ prop: 'test', anotherProp: true });