Is there an easy/best practice way to cast an any
value to a TypeScript Enum and throw an exception if there is no value.
As an example
You have an express request object and are using the query.option
value. Your application knows it only has two valid states a|b. However, the reality of the internet and request object is that it can be many things (undefined, a, b, foo).
enum OPTIONS_ENUM {
a = 'a',
b = 'b'
}
function handleRequest(req: Request): OPTIONS_ENUM {
// This will error because query.option is an any
return OPTIONS_ENUM[req.query?.option]
}
What I have been doing seems a little verbose. I have a "cast" function next to each enum that will throw if the ENUM does not have a value.
function castToOptionsEnum(option: any): OPTIONS_ENUM {
if (!Object.values(OPTIONS_ENUM)?.includes(option)) {
throw new Error(`Invalid Value for option, must be one of ${Object.values(OPTIONS_ENUM)}`)
}
// @ts-ignore
return OPTIONS_ENUM[option]
}
function handleRequest(req: Request) {
// This will error because the option query is unknowable
return castToOptionsEnum(req.query?.option)
}
CodePudding user response:
you can "simply" cast option
to OPTIONS_ENUM
when accessing OPTIONS_ENUM
in castToOptionsEnum
:
function castToOptionsEnum(option: any): OPTIONS_ENUM {
if (!Object.values(OPTIONS_ENUM)?.includes(option)) {
throw new Error(`Invalid Value for option, must be one of ${Object.values(OPTIONS_ENUM)}`);
}
return OPTIONS_ENUM[option as OPTIONS_ENUM];
}
This will remove any compile errors (I would suggest to remove // @ts-ignore
aswell, since it "hides" compile errors - but that's up to you ^^).