Last active
May 19, 2024 14:13
-
-
Save DarkGL/c332e086c336ce5cd0f4398bd423a885 to your computer and use it in GitHub Desktop.
Improve Runtime Type Safety with Branded Types in TypeScript
This file contains 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
declare const __brand: unique symbol | |
type Brand<B> = { [__brand]: B } | |
export type Branded<T, B> = T & Brand<B> | |
/** | |
* Branded type for a person's age, should belong to the interval [0, 125] (inclusive) | |
**/ | |
type Age = Branded<number, "Age">; | |
/** | |
* Validates the input number as a valid age, throws an error if it is not. | |
**/ | |
function createAge(input: number): Age { | |
if (input < 0 || input > 125) { | |
throw new Error("Input value for Age is not within the valid range") | |
} | |
return input as Age; | |
} | |
function getBirthYear(age: Age) { | |
return (new Date()).getFullYear() - age | |
} | |
/** Usage **/ | |
const myAge: Age = createAge(36); // true | |
const birthYear = getBirthYear(myAge) | |
const birthYear2 = getBirthYear(36) // This should show an error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment