Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map an enum to another enum in typescript?

I want to map one object's property that has an enum type to another object's property that is other enum type.

I've tried with type1.a as Enum2 or Enum2[type1.a] with no success.

Here is my simplified code problem:

enum Enum1 {
  N = 0,
  A = 1,
  B = 2
}

enum Enum2 {
  A = 1,
  B = 2
}

interface Type1 {
  a: Enum1;
}

interface Type2 {
  a: Enum2;
}

const type1: Type1 = {
  a: Enum1.A
};

const type2: Type2 = {
  a: type1.a
};

try it

Throws the error:

Type 'Enum1' is not assignable to type 'Enum2'.
(property) Type2.a: Enum2
like image 534
Alex Wehe Avatar asked Mar 27 '19 10:03

Alex Wehe


People also ask

Can you map an enum TypeScript?

Use the map() method with Enums in TypeScript # To use the map() method with enums: Use the Object. keys() method to get an array of the enum's keys.

Can enum extend another enum TypeScript?

The short answer is no, you can't extend enums because TypeScript offers no language feature to extend them.

Can you map an enum JavaScript?

Using `map()` on JavaScript Enums Since a JavaScript enum is just an object, you can iterate over an object using map() and Object.


1 Answers

You need to cast the type1.a prop to Enum2. To do this you need to use a "Type Guard".

Here is an example with your code:

enum Enum1 {
  N = 0,
  A = 1,
  B = 2
}

enum Enum2 {
  A = 1,
  B = 2
}

interface Type1 {
  a: Enum1;
}

interface Type2 {
  a: Enum2;
}

const type1: Type1 = {
  a: Enum1.N
};

function isEnum2(value: any): value is Enum2 {
  let isEnum2 = false;

  for (let key in Enum2) {
    if (Enum2[key] === value) {
      isEnum2 = true;
    }
  }

  return isEnum2;
}

if (isEnum2(type1.a)) {
  const type2: Type2 = {
    a: type1.a
  };
}

try it

When the isEnum2 function is used in the if block the prop type1.a becomes of type Enum2 inside that if block only.

Note: you could replace the content in the isEnum2 using for..in loop if you are using ES2017 or higher using Object.values:

return Object.values(Enum2).indexOf(value) > -1;

try it (Doesn't work in www.typescriptlang.org)

More info about Type Guards

like image 164
AlbertoFdzM Avatar answered Oct 08 '22 09:10

AlbertoFdzM