【发布时间】: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