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

TypeScript中如何通过函数根据Record键类型自动推断值类型?

解决方法

要实现调用函数时自动推断对应的值类型,只需将getAnimal改为泛型函数,让TypeScript根据传入的具体枚举成员推导返回值类型:

type Dog = 'dog';
type Cat = 'cat';
type Animal = Dog | Cat;

enum AnimalType {
  Dog,
  Cat,
}

const animalMap = {
  [AnimalType.Dog]: 'dog',
  [AnimalType.Cat]: 'cat',
} as const;

// 改为泛型函数,约束泛型T为AnimalType的子类型
const getAnimal = <T extends AnimalType>(type: T) => animalMap[type];

const dog = getAnimal(AnimalType.Dog); // 类型:'dog'(符合预期)
const cat = getAnimal(AnimalType.Cat); // 类型:'cat'(符合预期)

原理说明

  • 泛型T extends AnimalType限定参数type是AnimalType的某个具体成员,而非整个联合类型
  • 返回值animalMap[type]会被TypeScript推导为typeof animalMap[T],即对应枚举成员映射的具体字符串类型,而非所有可能值的联合类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:57:17