Can I define a Typescript map having a value constraint corresponding with each value's key?

孤人 提交于 2021-01-29 17:21:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!