Reputation: 3400
I have enum like:
enum MyEnum {
key1 = 'val1'
key2 = 'val2'
}
But I haven't idea how to implement SomeType
that does next thing:
const myFunction = (param: SomeType) => {
...
}
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
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