Given the following type definitions:
type BaseItem = {
name: string;
purchasedAt: string;
purchasePrice: number;
};
type AvailableItem = BaseItem;
type SoldItem = BaseItem & {
soldAt: string;
sellingPrice: number;
};
export type Item = AvailableItem | SoldItem;
Why doesn't TypeScript complain about the following expression?
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
and sellingPrice
should either both be present, or absent altogether. How would one make TypeScript to enforce this invariant?