Table of contents
- 1. Creating a Branded Type
- 2. Using a Branded Type
Branded types can help catch programming errors early in the development process by preventing values that don’t meet certain criteria from being passed into functions or used in certain contexts. They are a form of defensive coding in TypeScript and can ensure type validation.
Creating a Branded Type
To create a branded type in TypeScript, you start with an existing type and add a readonly property to it. This property is typically named
__type. Since this property is readonly, it’s not possible to directly annotate a variable with this type.
Using a Branded Type
Branded types are particularly powerful when used with assertion functions, which can validate an input and assert the branded type after successful validation.
This way you can rest assured that your variales and arguments will always be validated before being passed around.