How to know if incoming variable is of a specific enum type?

Issue

I have a class that has an overloaded constructor, where an input argument can be either a number, an instance of a certain class type, or a value of certain enum type:

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("...");
}

Now, apparently, when I execute the “typeof arg” in case an enum value is supplied, that evaluates to “number”, and not “PersonType”, so my code can’t work as expected.
Using instanceof for an enum type doesn’t work either, as it’s meant for object types only.

So, can anyone tell me how I can get to know when my input argument is of a specific enum type? What am i missing here?

Solution

So, can anyone tell me how I can get to know when my input argument is of a specific enum type?

It’s not possible. Look at the compiled code for the enum:

TypeScript:

enum PersonType { Type1, Type2 }

JavaScript:

var PersonType;
(function (PersonType) {
    PersonType[PersonType["Type1"] = 0] = "Type1";
    PersonType[PersonType["Type2"] = 1] = "Type2";
})(PersonType || (PersonType = {}));

At runtime, the enum PersonType is just a JavaScript object used as a map. Its members are strings and numbers. The enumeration of your example contains:

{
  "Type1": 0,
  "Type2": 1,
  "0": "Type1",
  "1": "Type2"
}

So, the members Type1 and Type2 in the enumeration, are true numbers:

console.log(PersonType.Type1) // 0

Answered By – Paleo

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.