You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript:根据对象类型动态更改函数返回类型

解决TypeScript函数根据参数动态推导返回类型的问题

要实现根据传入参数动态确定返回类型的getRecord函数,核心是使用泛型绑定参数类型与返回类型的关联。直接用Records[typeof record]无法生效的原因是,typeof record在非泛型函数中会被推断为keyof Records联合类型,导致返回类型变成Records[keyof Records](即user和device类型的联合),而非对应具体参数的单一类型。

正确实现代码

type Records = {
  user: {
    id: string;
    name: string;
    age: number;
  },
  device: {
    id: string;
    brand: string;
    manufacturer: string;
  }
}

function getRecord<T extends keyof Records>(record: T): Records[T] {
  // 替换为实际数据获取逻辑(如API请求、缓存读取等)
  const mockData: Records = {
    user: { id: 'u_001', name: '张三', age: 28 },
    device: { id: 'd_001', brand: '华为', manufacturer: '华为技术有限公司' }
  };
  return mockData[record];
}

效果验证

调用函数时,TypeScript会根据传入的具体参数自动推导返回类型:

// 返回类型自动推断为Records['user']
const userInfo = getRecord('user');
console.log(userInfo.age); // 类型提示为number,无报错

// 返回类型自动推断为Records['device']
const deviceInfo = getRecord('device');
console.log(deviceInfo.brand); // 类型提示为string,无报错

原理说明

泛型参数T被约束为keyof Records,确保传入的record参数只能是Records的合法键。函数返回类型Records[T]会随着T的具体值动态变化,实现了参数与返回类型的强绑定,让TypeScript能精准推断出对应类型。

内容的提问来源于stack exchange,提问作者aprilmintacpineda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:46:42