DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Upgrade Your Hobbyist Arduino Firmware To Work With STM32 For Wider Applications
  • Release Management Risk Mitigation Strategies in Data Warehouse Deployments
  • Data Excellence Unveiled: Mastering Data Release Management With Best Practices
  • Data Validation To Improve the Data Quality

Trending

  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • The Role of Functional Programming in Modern Software Development
  • Teradata Performance and Skew Prevention Tips
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  1. DZone
  2. Coding
  3. Languages
  4. Branded Types in TypeScript

Branded Types in TypeScript

This article takes a look at Branded types, which are a simple solution that improves code readability, reliability, and data validation.

By 
Sergio Carracedo user avatar
Sergio Carracedo
·
Dec. 23, 24 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
3.9K Views

Join the DZone community and get the full member experience.

Join For Free

When you model entities with TypeScript, it is very common to get an interface like this:

TypeScript
 
interface User {
  id: number
  username: string
  ...
}

interface Order {
  id: number
  userId: number
  title: string
  year: number
  month: number
  day: number
  amount: { currency: 'EUR' | 'USD', value: number }
  ...
}


The Problem

The properties’ types have no semantic meaning. In terms of types, User.id, Order.id, Order.year, etc. are the same: a number, and as a number they are interchangeable, but semantically, they are not.

Following the previous example, we can have a set of functions that do actions over the entities. For example:

TypeScript
 
function getOrdersFiltered(userId: number, year: number, month: number, day: number, amount: number) { // ...}

function deleteOrder(id: number) { // ... }


Those functions will accept any number in any arg no matter the semantic meaning of the number. For example:

TypeScript
 
const id = getUserId() 
deleteOrder(id)


Obviously, that is a big mistake, and it could seem easy to avoid reading the code, but the code is not always as simple as the example.

The same happens with getOrdersFiltered: we can swap the values of day and month, and we will not get any warning or error. The errors will happen if the day is greater than 12, but it is obvious that the result will not be the expected.

The Solution

Object calisthenics’ rules provide a solution for that: wrap all primitives and Strings (Related Primitive obsession anti-pattern). The rule is to wrap the primitives in an object that represents a semantic meaning (DDD describes that as ValueObjects).

But with TypeScript, we don’t need to use classes or objects for that: we can use the type system to ensure a number that represents something different from a year can’t be used instead of a year.

Branded Types

This pattern uses the extensibility of types to add a property that ensures the semantic meaning:

TypeScript
 
type Year = number & { __brand: 'year' }


This simple line creates a new type that can work as a number — but is not a number, it’s a year.

TypeScript
 
const year = 2012 as Year

function age(year: Year): number { //... }

age(2012) // ❌ IDE will show an error as 2012 is not a Year
age(year) // ✅ 


Generalizing the Solution

To avoid writing a type per branded type, we can create a utility type like:

TypeScript
 
declare const __brand: unique symbol
export type Branded<T, B> = T & { [__brand]: B }


That uses a unique symbol as the brand property name to avoid conflicts with your properties and gets the original type and the brand as generic parameters.

With this, we can refactor our models and functions as follows:

TypeScript
 
type UserId = Branded<number, 'UserId'>
type OrderId = Branded<number, 'OrderId'>
type Year = Branded<number, 'Year'>
type Month = Branded<number, 'Month'>
type Day = Branded<number, 'Day'>
type Amount = Branded<{ currency: 'EUR' | 'USD', value: number}, 'Amount'>

interface User {
  id: UserId
  username: string
  ...
}

interface Order {
  id: OrderId
  userId: UserId
  title: string
  year: Year
  month: Month
  day: Day
  amount: Amount
  ...
}

function getOrdersFiltered(userId: UserId, year: Year, month: Month, day: Day, amount: Amount) { // ...}
function deleteOrder(id: OrderId) { // ... }


Now, in this example, the IDE will show an error as id is a UserId and deleteOrder expects an OrderId.

TypeScript
 
const id = getUserId() 
deleteOrder(id) // ❌ IDE will show an error as id is UserID and deleteOrder expects OrderId


Trade-Offs

As a small trade-off, you will need to use X as Brand. For example, const year = 2012 as Year when you create a new value from a primitive, but this is the equivalent of a new Year(2012) if you use value objects. You can provide a function that works as a kind of “constructor”:

TypeScript
 
function year(year: number): Year {
  return year as Year
}


Validation With Branded Types

Branded types are also useful to ensure the data is valid as you can have specific types for validated data, and you can trust the user was validated just by using types:

TypeScript
 
type User = { id: UserId, email: Email}
type ValidUser = Readonly<Brand<User, 'ValidUser'>>


function validateUser(user: User): ValidUser {
  // Checks if user is in the database
  if (!/* logic to check the user is in database */) {
    throw new InvalidUser()
  }
  
  return user as ValidUser
}

// We can not pass just a User, needs to be a ValidUser
function doSomethingWithAValidUser(user: ValidUser) {
  
}


Readonly is not mandatory, but to be sure your code will not change the data after validating it, it’s very recommended.

Recap

Branded types are a simple solution that includes the following:

  • Improves the code readability: Makes clearer which value should be used in each argument
  • Reliability: Helps to avoid mistakes in the code that can be difficult to detect; now the IDE (and the type checking) help us to detect if the value is in the correct place
  • Data validation: You can use branded types to ensure the data is valid.

You can think of Branded types as a kind of version of ValueObjects but without using classes — just types and functions.

Enjoy the power of typings!

Data validation Integrated development environment Type system TypeScript Data (computing)

Published at DZone with permission of Sergio Carracedo. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Your Hobbyist Arduino Firmware To Work With STM32 For Wider Applications
  • Release Management Risk Mitigation Strategies in Data Warehouse Deployments
  • Data Excellence Unveiled: Mastering Data Release Management With Best Practices
  • Data Validation To Improve the Data Quality

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!