问题
In this playground I would like to create a map containing at most a single action of each type in the Action union. Each of the unioned types is differentiated by having a different string literal property 'type'. I have a definition for this map which compiles but is too loose...
const lastAction:{
[A in Action["type"]]?:Action
} = {}
The constraint on keys within the lastAction
map enforces that...
- the key is a "type" property from some Action type
- the value must be some Action type
...it doesn't currently enforce that the key and the value are from the same Action type. Ideally the last line of the playground would fail as a compiler error as it attempts to assign an Action having type "snooze" into a property with the name "fulfil".
lastAction["fulfil"]=snoozeAction
I'm just missing the obvious here. I'm certain there's some way to do this with distributive conditionals or something even simpler. The pseudo-code below is junk Typescript as Generics don't work on a per property basis like this but it gives an idea of what I'm after...
const lastAction: {
[key:A["type"]]:A extends Action
} = {};
回答1:
With Typescript 4.1's key remapping, this is incredibly easy:
const lastAction:{
[A in Action as A["type"]]?: A
} = {}
来源:https://stackoverflow.com/questions/65365760/can-i-define-a-typescript-map-having-a-value-constraint-corresponding-with-each