I'm implementing a simple state machine. The configuration is as follows:
type StateMachineConfig<State extends string, TransitionState extends State> = Record<State, TransitionState[]>;
Each key should be a string enumeration.
Each value should be an array of the same string enumeration, but the State given as a key should not be included in the array
Thus the following status is considered:
enum MyStates { State1 = "State 1", State2 = "State 2", State3 = "State 3" }
...the following should work:
const config: StateMachineConfig<MyStates, MyStates> = { [MyStates.State1]: [MyStates.State2], [MyStates.State2]: [MyStates.State3], [MyStates.State3]: [MyStates.State1, MyStates.State2] }
...but not the following:
const config: StateMachineConfig<MyStates, MyStates> = { [MyStates.State1]: [MyStates.State2], [MyStates.State2]: [MyStates.State3], [MyStates.State3]: [MyStates.State2, MyStates.State3] // error: value in array is same as key }
P粉8648728122023-09-17 00:42:18
You can use mapping types and excludes
for this:
type StateMachineConfig<State extends string, TransitionState extends State> = { [state in State]: Exclude<TransitionState, state>[]; };