TypeScript: Branded Types 🔧

submited by
Style Pass
2024-04-24 17:00:36

Ahoy there TypeScript warriors! 👋 Today we're extending our work in the TypeScript mapped types article to provide branding. The previous article discussed how to use TypeScript mapped types in a nominal rather than structural nature.

This is a fancy way of saying TypeScript is structural by default, i.e. it will see type A and B as equal when dealing with types. Making type A and B nominal would make TypeScript differentiate them apart, even though their structure is the same.

In this post, we're building on that work to produce a way to brand a type, providing an automated and easy-to-use way of making a type nominal. Branding focuses on the type system only, rather than introducing runtime fields like in the previous post, which is a major benefit over the previous approach.

Branding, also known as opaque types, enable differentiation of types in TypeScript which otherwise would be classified as the same type. For example

Leave a Comment