在TypeScript接口中使用字符串枚举值作为计算属性键
问题描述:
我想定义一个函数,根据我给出的键值返回不同类型的对象。这基本上就像在createElement
功能在TypeScript接口中使用字符串枚举值作为计算属性键
https://github.com/Microsoft/TypeScript/blob/master/lib/lib.dom.d.ts#L3117
但是这里使用的伎俩,而不是字符串文字,我想用字符串枚举类型,而不是。所以我写了这样的事情
class Dog {}
class Cat {}
class Bird {}
enum Kind {
Dog = 'Dog',
Cat = 'Cat',
Bird = 'Bird'
}
interface KindMap {
[Kind.Dog]: Dog
[Kind.Cat]: Cat
[Kind.Bird]: Bird
}
function getAnimal<K extends keyof KindMap> (key: K): KindMap[K] {
switch (key) {
case Kind.Dog:
return new Dog()
case Kind.Cat:
return new Cat()
case Kind.Bird:
return new Bird()
}
}
然而,打字稿似乎不喜欢我把里面的接口enum Kind
的值作为计算财产的方式,它抱怨
A computed property name in an interface must directly refer to a built-in symbol.
这里谈到的问题,我已经有了在枚举中定义的常量,我不喜欢使用字符串字面量,有没有一种方法可以使这个工作?这意味着使用Kind枚举的值作为KindMap
中的计算属性键。
答
有时keyof
一个简单的对象比打字稿枚举简单:
class Dog { }
class Cat { }
const kindMap = {
Dog,
Cat
};
type KindMap = typeof kindMap;
function getAnimalClass<K extends keyof KindMap>(key: K): KindMap[K] {
return kindMap[key];
}
// These types are inferred correctly
const DogClass = getAnimalClass('Dog');
const dog = new DogClass();
const CatClass = getAnimalClass('Cat');
const cat = new CatClass();
Try it in TypeScript Playground
我试图执行getAnimal()
与映射类型,但似乎碰到车的推论。但是,查看课程更容易。
内联getAnimalClass
查找还与类型推断:
const dog = new kindMap['Dog']();
[这是不支持](https://github.com/Microsoft/TypeScript/issues/16258)在当前版本的打字稿,看起来像[它可能会在2.7中修复](https://github.com/Microsoft/TypeScript/pull/15473) – artem