I want to define a function returns different type of object based on the key I give. It's basically like the trick used here in createElement
function
https://github.com/Microsoft/TypeScript/blob/master/lib/lib.dom.d.ts#L3117
However, instead of string literal, I want to use string enum type instead. So I wrote something like this
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()
}
}
However, TypeScript seems doesn't like the way I put the enum Kind
's value inside interface as the computed property, it complains
A computed property name in an interface must directly refer to a built-in symbol.
Here comes the question, I already have the constants defined in the enum, I don't like to use string literal, is there a way I can make this works? Which means use the Kind enum's value as the computed property key in the KindMap
.