仅部分符合给定联合类型的数据-为什么TypeScript不抱怨?

仅部分符合给定联合类型的数据-为什么TypeScript不抱怨?,typescript,types,typechecking,static-typing,union-types,Typescript,Types,Typechecking,Static Typing,Union Types,给定以下类型定义: type BaseItem = { name: string; purchasedAt: string; purchasePrice: number; }; type AvailableItem = BaseItem; type SoldItem = BaseItem & { soldAt: string; sellingPrice: number; }; export type Item = AvailableItem | SoldItem

给定以下类型定义:

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强制执行此不变量?

我对TypeScript的结构化键入系统不太熟悉,无法解释为什么会出现这种情况,但我认为没有任何方法使TypeScript强制执行现有的类型

获得所需类型安全性的方法是使用有区别的联合,其中所有类型都具有公共常量属性,例如一个种类键。下面的代码将在示例中的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;
有关歧视工会的更多信息,请参见