search

Home  >  Q&A  >  body text

Limit array values ​​in a generic record to not contain the same value as the key it is assigned to?

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粉252116587P粉252116587439 days ago753

reply all(1)I'll reply

  • P粉864872812

    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>[];
    };

    (Online Demo)

    reply
    0
  • Cancelreply