Simcha
Simcha

Reputation: 3400

Bidirectional enum in TS

I have enum like:

enum MyEnum {
   key1 = 'val1'
   key2 = 'val2'
}

But I haven't idea how to implement SomeType that does next thing:

  1. Function:
const myFunction = (param: SomeType) => {
   ...
}
  1. Should support next usages:
myFunction(MyEnum.key1) // <- gets also enum 
myFunction('val1') // <- gets also values of enum
myFunction('someOtherValue') // <- Error

P.S. Or at least if enums keys and values identical to get it keys instead of values

Upvotes: 2

Views: 927

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97312

In TypeScript 4.1 or later, you can a̶b̶u̶s̶e̶ use a template literal type to achieve this:

enum MyEnum {
   key1 = 'val1',
   key2 = 'val2'
}

const myFunction = (param: MyEnum | `${MyEnum}`) => {
   // ...
}

myFunction(MyEnum.key1); // OK
myFunction('val1'); // OK
myFunction('val3'); // Error

Upvotes: 4

Related Questions