Last active
July 24, 2018 13:48
-
-
Save edwingustafson/44ad18880a5b1e76e904cd83b8673839 to your computer and use it in GitHub Desktop.
Nominal typing with brands
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
| // Adapted from https://michalzalecki.com/nominal-typing-in-typescript/ | |
| // see also "Flavoring" https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/ | |
| type Brand<K, T> = K & { __brand: T }; | |
| type CatalogNumber = Brand<string, 'catalogNumber'>; | |
| type CasNumber = Brand<string, 'casNumber'>; | |
| const pge2CatalogNumber: CatalogNumber = '14010' as CatalogNumber; | |
| const pge2CasNumber: CasNumber = '363-24-6' as CasNumber; | |
| // Functions (with dummy implementations) requiring specific branded types | |
| const validateCatalogNumber: (s: CatalogNumber) => boolean = (s) => true; | |
| const validateCasNumber: (s: CasNumber) => boolean = (s) => true; | |
| console.log(validateCatalogNumber(pge2CatalogNumber)); | |
| // Fails to compile, incompatible types | |
| console.log(validateCasNumber(pge2CatalogNumber)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment