Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 491
KoenT_X Avatar asked Jun 24 '16 13:06

KoenT_X


1 Answers

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
like image 75
Paleo Avatar answered Jan 05 '23 04:01

Paleo