【发布时间】:2022-02-21 18:33:15
【问题描述】:
我有一个具有重载构造函数的类,其中输入参数可以是数字、某个类类型的实例或某个枚举类型的值:
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("...");
}
现在,显然,当我在提供枚举值的情况下执行“typeof arg”时,计算结果为“number”,而不是“PersonType”,因此我的代码无法按预期工作。 对枚举类型使用 instanceof 也不起作用,因为它仅适用于对象类型。
那么,谁能告诉我如何知道我的输入参数何时属于特定枚举类型?我在这里错过了什么?
【问题讨论】:
标签: typescript