Created
February 20, 2025 12:49
-
-
Save Armenvardanyan95/6176706cc48794598155ed01ca6a05d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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