检查变量是否是联合类型的子类型

Check if variable is a child type of type union

假设我有 2 个枚举:哺乳动物和鱼类

enum Mammal {
    bear = 'bear', 
    human = 'human'
}
enum Fish { 
    salmon = 'salmon', 

}

然后我合并了那些枚举:

const Animal = { Mammals, Fish };
type Animal = Mammals | Fish;

将变量类型转换为该父项时,我如何找到它所属的子枚举?

let animal = <Animal>'salmon'

基本上我想要的是这样的:

if (typeof <Animal> 'salmon' == typeof Mammal) {
//do stuff...
}

没有什么可以阻止相同的值出现在多个 'child' 枚举中,因此没有逻辑的方式来推断这一点。此外,typeof 用作这样的语句时,将始终为您提供 'string'.

另一种方法是使用带有继承的 classes,这样 intanceof 就可以用于比较。您可以使用将字符串映射到正确子 class 的工厂函数来创建实例。