- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
Here是带有此问题代码的 Typescript Playground ,也在下方。
本质上
enum Color {
Red = "RED",
Orange = "ORANGE"
}
enum Package {
Single = "SINGLE",
Multiple = "MULTIPLE"
}
export interface ShipmentSingle {
id: string;
color: Color,
package: Package.Single
}
export interface ShipmentMultiple {
id: string;
color: Color,
package: Package.Multiple,
quantity: number
}
type Shipment = ShipmentSingle | ShipmentMultiple
const s: Shipment = {
id: '1',
color: Color.Red,
package: Package.Single
}
const addIdToOrder = (shipment: Omit<Shipment, 'id'>): Shipment => ({
...shipment,
id: '2'
})
我看到了错误
Type '{ id: string; color: Color; package: Package; }' is not assignable to type 'Shipment'. Property 'quantity' is missing in type '{ id: string; color: Color; package: Package; }' but required in type 'ShipmentMultiple'.
这是为什么?
最佳答案
错误发生是因为 Omit
内部使用 keyof T
. keyof T
当应用于联合类型时(Shipment
是联合类型)仅返回存在于联合组成的两种类型中的键。
type Keys = keyof Shipment; // Keys = 'id' | 'color' | 'package'.
原因是described here .
所以 Omit<Shipment, 'id'>
使用 color
生成对象和 package
特性。 quantity
不存在。
要解决这个问题,我可能会推荐使用 distributive conditional types首先分发Shipment
至 ShipmentSingle
和 ShipmentMultiple
然后申请Omit
给他们每个人。所以结果将再次是联合类型。
type OmitWithDistribution<T, K extends keyof T> = T extends any ? Omit<T, K> : never;
const addIdToOrder = (shipment: OmitWithDistribution<Shipment, 'id'>): Shipment => ({
...shipment,
id: '2'
})
关于typescript - 我有一个类型,它是两个接口(interface)的联合,只有一个属性不同,当我省略一个公共(public)属性并将其添加回来时,为什么 TS 无法识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57152890/
我对 Objective C 和 iOS 开发总体来说是新手。我正在尝试创建一个应用程序,它会发出 http 请求并在标签上显示内容。 当我开始测试时,我注意到标签是空白的,尽管我的日志显示我已经恢复
我实现了一个 MVP 应用程序。后退按钮工作正常。我想以编程方式回到以前的地方。我该怎么做? 我正在寻找类似的东西: clientFactory.getPlaceController().goBack
我想从 mySubView 制作后退按钮。我有带有按钮的付款ViewController,这个按钮使view.addSubview(WkWebView)。所以我可以打开 WkWebView 但我不可能
我有一个 master 分支,里面有很多不会发布的特性。我被要求从 master 中删除这些功能并创建一个包含它们的新分支,以便我们稍后可以 merge 回 master。 我采取的步骤是: 在 ma
如何禁用页面上的所有 onclick 事件,绑定(bind)我的自定义函数,并在执行后启用所有之前的事件? 我正在构建一个小书签,它应该适用于任何已加载的页面,并且我正在使用 jQuery 来处理我的
我正在尝试从 Spotify api 接收 token 。不幸的是,我一直收到 415。你能帮帮我,让我知道我做错了什么吗? const axios = require('axios'); const
我有一个提供上下文的函数: def buildContext(s:String)(request:RequestHeader):Future[Granite.Context] = { ....
我有一个列表,其中包含几个不同形状的 numpy 数组。我想将这个数组列表 reshape 为一个 numpy 向量,然后更改向量中的每个元素,然后将其 reshape 回原始数组列表。 例如: 输入
我目前有这个工作 fiddle - http://jsfiddle.net/B8Abd/ 我想在函数中使用 jquerys 淡出然后淡入。目前的代码是这样的: function chan
我有 2 个分支,一个是 main 分支,另一个是我正在开发一个 parallel 版本。 A --> B --> C (master) \ -> E --> F (parallel) pa
我试图从我的“ super 项目”中的文件目录中创建一个“子项目”以与其他人一起工作,但我一直在努力使其在 git subtree 中工作。 理想情况下,其他人可以在子项目上工作,然后我从上游更改中提
有没有其他人看到这个? 我正在使用带有回形针的 rails 3,当我上传 .doc 时,它的应用程序/msword 效果很好,但是当我上传 .docx 时,content_type 被保存为应用程序/
我是一名优秀的程序员,十分优秀!