gpt4 book ai didi

typescript - 我有一个类型,它是两个接口(interface)的联合,只有一个属性不同,当我省略一个公共(public)属性并将其添加回来时,为什么 TS 无法识别?

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:57 26 4
gpt4 key购买 nike

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首先分发ShipmentShipmentSingleShipmentMultiple然后申请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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com