Skip to content

Instantly share code, notes, and snippets.

@Armenvardanyan95
Created February 20, 2025 12:49
Show Gist options
  • Save Armenvardanyan95/6176706cc48794598155ed01ca6a05d6 to your computer and use it in GitHub Desktop.
Save Armenvardanyan95/6176706cc48794598155ed01ca6a05d6 to your computer and use it in GitHub Desktop.
type ModelTypes = 'product' | 'order';
type Product = {productName: string};
type Order = {orderId: number};
type Model = {
id: number;
type: ModelTypes;
entity: Product | Order;
}
const model: Model = {
id: 1,
type: 'order',
entity: {
// see, a mistake, the type is `order`,
// but we actually have a product here
productName: 'Product'
}
}
if (model.type === 'product') {
// this will give us an error as the type is `Product | Order`
console.log(model.entity.productName);
}
// instead, use discriminated unions:
type Model = {
id: number;
} & ({type: 'order', entity: Order} | {type: 'product', entity: Product});
const model: Model = {
id: 1,
type: 'order',
entity: {
// now, we'll get an error here,
// as `productName` is incompatible with type `order`
productName: 'Product'
}
}
if (model.type === 'product') {
// no error here, type `product` ensure the `entity` field is a `Product`
console.log(model.entity.productName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment