I've ran into a little issue when working with enums in TypeScript. My scenario is this:
- I have defined a string enum containing allowed values
- I have defined a method that accepts any incoming value (of
string
type), and have to cast it to the said enum
The problem is that even after checking if the incoming value
from the method, intellisense tells me that value
is still type of string
instead of the enum. How can I force value
to be a type of AllowedValues
?
Here is a proof-of-concept example:
/** enum */
enum AllowedValues {
LOREM_IPSUM = 'lorem ipsum',
DOLOR_SIT = 'dolor sir',
AMET = 'amet'
}
/** @method */
function doSomething(value: string = AllowedValues.LOREM_IPSUM) {
// If value is not found in enum, force it to a default
if (!(Object as any).values(AllowedValues).includes(value))
value = AllowedValues.LOREM_IPSUM;
// Value should be of type `AllowedValues` here
// But TypeScript/Intellisense still thinks it is `string`
console.log(value);
}
doSomething('amet'); // Should log `amet`
doSomething('aloha'); // Should log `lorem ipsum`, since it is not found in `AllowedValues`
You can also find it on TypeScript playground.