【问题标题】:Given record key type, infer record value type给定记录键类型,推断记录值类型
【发布时间】:2022-08-10 00:16:41
【问题描述】:

我不知道这是否可能,但我的目标是:给定记录键的类型,我想在使用函数时自动推断值的类型:

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

enum AnimalType {
  Dog,
  Cat,
}

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

const getAnimal = (type: AnimalType) => animalMap[type];

const dog = getAnimal(AnimalType.Dog); // type: \'dog\' | \'cat\'. desired type: \'dog\'
const cat = animalMap[AnimalType.Cat]; // type: \'cat\'

我想使用上面的功能而不是直接使用地图。这是一个简化的例子。

    标签: typescript


    【解决方案1】:

    如果您希望 TypeScript 跟踪传递给 getAnimal()AnimalType 的特定子类型,您需要 getAnimal() 在该类型中为 generic。如果type 只是AnimalType 类型,那么这就是编译器所知道的全部。相反,您希望它是通用类型 T constrainedAnimalType

    const getAnimal = <T extends AnimalType>(type: T) => animalMap[type];
    
    const dog = getAnimal(AnimalType.Dog); // type: 'dog'
    

    Playground link to code

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多