如何根据泛型属性 Select 类型?
enum AnimalType {
DOG,
CAT,
FROG,
SNAKE,
}
const dog = {
type: AnimalType.DOG, // type property exists for all animals. other properties are vary for different animals
legs: 4,
}
const cat = {
type: AnimalType.CAT,
tail: 1,
}
const frog = {
type: AnimalType.FROG,
canSwim: true,
tail: 0,
}
const snake = {
type: AnimalType.SNAKE,
tail: 'looong',
age: 2,
}
type Animal<AnimalType> = typeof dog | typeof cat | typeof frog | typeof snake // how to rewrite this type definition?
如何根据AnimalType推断类型?例如,Animal<AnimalType.DOG>
应该等于typeof dog
对于条件类型,这是可能的:
type Animal<T extends AnimalType> = T extends AnimalType.DOG ? typeof dog : T extends AnimalType.CAT ? typeof cat : T extends AnimalType.FROG ? typeof frog : T extends AnimalType.SNAKE ? typeof snake : unknown
但它看起来太长了,完全无法阅读.我希望有一个更好的解决方案