I'm trying to constrain the acceptable string values for a property on an interface. The intuitive way was to use an enum which was confirmed after googling around in posts like this. But when iterating over the enum to populate that property of the interface I get Type 'string' is not assignable to type 'EventTypes | undefined'
.
Code:
export enum EventTypes {
a = 'a',
b = 'b',
...
}
export interface GetEventsParams {
event_type?: EventTypes;
...
}
for (const toDate of dates) {
for (const eventType in EventTypes) {
params.push({
fromDate,
toDate,
baseParams: { event_type: eventType }
})
}
}
Is there a different way to iterate over the EventTypes values that makes typescript recognize its one of EventTypes? What's the recommended way to accomplish this?
PS:
One way to make it stop complaining, adding { event_type: eventType as EventTypes }
, seems hacky but is this the recommended way to solve the issue. And I'd rather not duplicate the strings into a type like "value" | "value2"
seeing as I use the enum elsewhere and having to change values in multiple locations instead of just once in the enum is not ideal.