给出以下类型定义:
type BaseItem = {
name: string;
purchasedAt: string;
purchasePrice: number;
};
type AvailableItem = BaseItem;
type SoldItem = BaseItem & {
soldAt: string;
sellingPrice: number;
};
export type Item = AvailableItem | SoldItem;
为什么TypeScript不抱怨以下表达式?
const invalidItem: Item = {
name: "foobar",
purchasedAt: "1-1-2019",
purchasePrice: 42,
soldAt: "5-1-2019"
// `sellingPrice` should be here, or `soldAt` should be absent
};
soldAt
和sellingPrice
应该都存在或完全不存在。如何使TypeScript强制执行此不变式?
我对打字稿的结构化打字系统还不够熟悉,无法解释为什么会发生这种情况,但是我不相信有任何方法可以使打字稿在拥有打字稿时强制执行类型。
获得所需类型安全性的方法是使用区分联合(所有类型具有共同的常量属性,例如kind
键)。在您的示例中,以下代码将在invalidItem
对象上出错。
type AvailableItem = {
kind: "base";
name: string;
purchasedAt: string;
purchasePrice: number;
}
type SoldItem = {
kind: "sold";
name: string;
purchasedAt: string;
purchasePrice: number;
soldAt: string;
sellingPrice: number;
}
export type Item = AvailableItem | SoldItem;
请参见https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions,更多有关使用已区分的并集的操作。