小编Koe*_*T_X的帖子

如何知道传入变量是否属于特定的枚举类型?

我有一个具有重载构造函数的类,其中输入参数可以是数字,某个类类型的实例或某个枚举类型的值:

class Person { name: string; };
enum PersonType { Type1, Type2 };

constructor(id: number);
constructor(person: Person);
constructor(personType: PersonType);
constructor(arg: string | Person | PersonType)
{
    if (typeof arg === "number") { /* do number stuff */ }
    else if (arg instanceof Person) { /* do Person stuff */ }
    else if (typeof arg === "PersonType") { /* do PersonType stuff */ }
    else throw new MyException("...");
}
Run Code Online (Sandbox Code Playgroud)

现在,很显然,当我在一个枚举值提供情况执行"的typeof ARG",计算结果为"数字",而不是"PersonType",所以我的代码不能正常工作.使用instanceof作为枚举类型也不起作用,因为它仅适用于对象类型.

那么,有人能告诉我当输入参数是特定的枚举类型时我怎么知道的?我在这里失踪了什么?

typescript

7
推荐指数
1
解决办法
2817
查看次数

标签 统计

typescript ×1