Limit array values in a generic record to not contain the same value as the key it is assigned to?
P粉252116587
P粉252116587 2023-09-16 14:13:52
0
1
684

I'm implementing a simple state machine. The configuration is as follows:

type StateMachineConfig = Record;

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.State1]: [MyStates.State2], [MyStates.State2]: [MyStates.State3], [MyStates.State3]: [MyStates.State1, MyStates.State2] }

...but not the following:

const config: StateMachineConfig = { [MyStates.State1]: [MyStates.State2], [MyStates.State2]: [MyStates.State3], [MyStates.State3]: [MyStates.State2, MyStates.State3] // error: value in array is same as key }

P粉252116587
P粉252116587

reply all (1)
P粉864872812

You can use mapping types andexcludesfor this:

type StateMachineConfig = { [state in State]: Exclude[]; };

(Online Demo)

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!