Access the value of an enum from an interface

Viewed 10

I have an interface that types the data of a form.

interface ExpenseFormValuesInterface {
  name: string,
  requestTypes: RequestTypeOptionsEnum[],
  ...many other enum properties...
}

This interface has many enums that are only used there, so I would like to be able to use them like this in the form:

<Select >
  <Option value={ExpenseFormValuesInterface["requestTypes"].ALL} />
  <Option value={ExpenseFormValuesInterface["requestTypes"].PURCHASE} />
  <Option value={ExpenseFormValuesInterface["requestTypes"].INVOICE} />
  ...
<Select />

This will help me not having to export globally the enums that are only used in this particular form. I don't like the of having so many enums for a specific form in my global scope, and also I would like to keep enum names short and scoped to the FormValueInterface file. Else enums should be called something like "ExpenseFormRequestTypeOptionsEnum" instead of just "RequestTypeOptionsEnum".

What I did so far was to create an object with all the enums of the interface, and exported it along the interface.

export const expenseFormEnums = {
    requestTypes: RequestTypeOptionsEnum,
    condition: ConditionOptionsEnum,
    currency: CurrencyOptionsEnum,
    comparison: ComparisonOperatorEnum,
    approverType: ApproverTypeEnum,
}

And then use them in the form.

<Select >
  <Option value={expenseFormEnums.requestType.ALL} />
  <Option value={expenseFormEnums.requestType.PURCHASE} />
  <Option value={expenseFormEnums.requestType.INVOICE} />
  ...
<Select />

I would like to know if there is a way to avoid creating this object and access the enums directly from the interface somehow.

0 Answers
Related