我正在实现一个简单的状态机。配置如下所示:
type StateMachineConfig<State extends string, TransitionState extends State> = Record<State, TransitionState[]>;
每个键都应该是一个字符串枚举。
每个值都应该是相同字符串枚举的数组,但是作为键给出的 State 不应包含在数组中
因此考虑到以下状态:
enum MyStates { State1 = "State 1", State2 = "State 2", State3 = "State 3" }
...以下应该有效:
const config: StateMachineConfig<MyStates, MyStates> = { [MyStates.State1]: [MyStates.State2], [MyStates.State2]: [MyStates.State3], [MyStates.State3]: [MyStates.State1, MyStates.State2] }
...但不是以下内容:
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
您可以为此使用映射类型和排除
:
type StateMachineConfig<State extends string, TransitionState extends State> = { [state in State]: Exclude<TransitionState, state>[]; };
(在线演示)