In this scenario, there is an enum called Process which consists of different steps represented by enums such as SimpleStep and AdvancedStep.
enum Process {
Simple = "simple",
Advanced = "advanced"
}
enum SimpleStep {
A = "A",
B = "B"
}
enum AdvancedStep {
A = "A",
B = "B",
C = "C"
}
To create an array of steps using the provided statements:
const SIMPLE_STEPS = Object.keys(SimpleStep).map(
(k: string) => SimpleStep[k]
);
const ADVANCED_STEPS = Object.keys(AdvancedStep).map(
k => AdvancedStep[k]
);
const ALL_STEPS = {
[Process.Simple]: SIMPLE_STEPS,
[Process.Advanced]: ADVANCED_STEPS
};
A function was written to determine the step number based on the process used.
// ???: Check if S is a step of Process
const getStepNumber = <P extends Process, S>(process: P, step: S) => {
return ALL_STEPS[process].indexOf(step) + 1;
};
// returns 2, correct result
console.log('step number of B', getStepNumber(Process.Advanced, AdvancedStep.B));
// returns 0. Is it possible to prevent at compile-time?
console.log('step number of C', getStepNumber(Process.Simple, AdvancedStep.C));
The code sample begs the question of whether it is feasible to use generics to safeguard against calling the function with incorrect steps at compile time.
If you want to experiment with the complete example, feel free to access the playground through this link: TS Playground