In my opinion, the following approach works better in TypeScript compared to using Enums. I am looking for a way to simplify this process, perhaps by using a utility type. It would be ideal if we could define Enums to function in a similar way, but unfortunately, that doesn't seem to be possible as far as I know.
Current code explanation:
StepWizardEventType
restricts the possible values for an event type, and the const
is utilized to access these values in the code. The type of the const
{ [prop: string]: StepWizardEventType }
allows variables/properties to be of type StepWizardEventType
and assigned one of the values from the const stepWizardEventTypes
.
export type StepWizardEventType = 'cancel' | 'create' | 'init' | 'next' | 'previous' | 'reset' | 'save';
export const stepWizardEventTypes: { [Property in StepWizardEventType]: StepWizardEventType } = {
cancel: 'cancel',
create: 'create',
init: 'init',
next: 'next',
previous: 'previous',
reset: 'reset',
save: 'save',
};
export interface StepEvent {
type: StepWizardEventType;
}
// somewhere else in another file...
const event: StepEvent = {
type: stepWizardEventTypes.cancel // compiler doesn't complain here! yay!
}
EDIT: The compiler raises issues with the example enum usage.
export enum EventTypes {
cancel = 'cancel',
create = 'create'
}
type EventType = 'cancel' | 'create';
interface Dodad {
eventType: EventType;
}
const doDadInstance: Dodad = {
eventType: EventTypes.cancel // TypeScript complains here for enums
}