我可以定义一个Typescript映射,该映射具有与每个值的键对应的值约束吗? [英] Can I define a Typescript map having a value constraint corresponding with each value's key?

查看:121
本文介绍了我可以定义一个Typescript映射,该映射具有与每个值的键对应的值约束吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此游乐场我想创建一个地图,其中最多包含一个动作"联合中每种类型的单个动作.每个联合类型的区别在于具有不同的字符串文字属性"type".我为此地图定义了一个可编译但过于宽松的地图...

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 
} = {}

lastAction映射中的键约束强制执行...

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

...目前,不是强制要求键和值来自 相同 操作类型.理想地,游乐场的最后一行将由于编译器错误而失败,因为它试图分配具有"snooze"类型的动作.放入名为"fulfil"的属性中.

...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

我只是在这里想不到.我敢肯定,有一些方法可以通过分配条件或更简单的方法来做到这一点.下面的伪代码是垃圾Typescript,因为泛型无法像这样在每个属性上工作,但它可以让我了解...

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
} = {};

推荐答案

使用Typescript 4.1的

With Typescript 4.1's key remapping, this is incredibly easy:

const lastAction:{
    [A in Action as A["type"]]?: A 
} = {}

这篇关于我可以定义一个Typescript映射,该映射具有与每个值的键对应的值约束吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆