Given this enumeration:
export enum Example {
First = 'A',
Second = 'B'
}
Is there a way to construct a type such that the type is 'A' | 'B'
?
I know that keyof typeof Example
will get me 'First' | 'Second'
, but I want the values, not the keys.
The use case is that we have enumerations in the code in the client. These values are sent down from the server as strings in the JSON. I want to type the JSON payload as an interface but have the property typed as a string to match the enumeration values.
I realize I could do this:
export interface Payload {
someProp?: Example;
}
But then in unit tests, we cannot simply copy a payload into the Typescript without errors:
const examplePayload: Payload = { someProp: 'A' }
Results in the error:
Type '"A"' is not assignable to type 'Example | undefined'.ts(2322)
So I'd like to allow it to be the values of the enum, but without hardcoding it like this that would cause maintenance issues when that enum is changed and the type wasn't changed:
const examplePayload: Payload = { someProp: 'A' | 'B' }
Unfortunately I cannot do this to get it cast as a string:
export type EnumValues<Type> = `${Type[keyof Type]}`;
const s: EnumValues<typeof Example>;
Results in:
Type 'Type[keyof Type]' is not assignable to type 'string | number | bigint | boolean | null | undefined'.
I also do not want to use 'A' | 'B'
in code as the server values are not always obvious and it is much easier to maintain the code with an enumeration serving as server valid values aliases.