I have an enum
in TypeScript.
I want to write a function that returns an exhaustive array that contains exactly one reference to each property on the enum.
The return of the function will be an Array<{ id: EnumValue, label: string }>
.
Sample code:
// I have this enum:
enum StepId {
STEP_ONE = 'step-one-id',
STEP_TWO = 'step-two-id',
}
// I want to define some function...
function someFunc() {
return ...
}
// which returns an Array where every value from `StepId` is represented as an object with that value as the `id` field.
someFunc() === [
{ id: CustomStepIds.STEP_ONE, label: 'Step One', },
{ id: CustomStepIds.STEP_TWO, label: 'Step Two', },
];
I have tried to first solve the problem of enforcing all enum values are represented in an array. I've tried this:
enum CustomStepId {
STEP_ONE = 'step-one-id',
STEP_TWO = 'step-two-id',
}
type ValueOf<T> = T[keyof T];
const stepConfig: Array<{ id: ValueOf<typeof CustomStepId>, label: string }> = [
{ id: CustomStepId.STEP_ONE, label: 'Step One', },
{ id: CustomStepId.STEP_TWO, label: 'Step Two', },
{ id: CustomStepId.STEP_TWO, label: 'Step Two', }, // this should error, as STEP_TWO is already defined
];
However as noted in the comment above, while this enforces id
is a CustomStepId
, it does not enforce uniqueness of the field.