我正在實作一個簡單的狀態機。配置如下所示:
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>[]; };
(線上示範)