Branded Types in TypeScript

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

TypeScript

 

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

 

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

TypeScript

 

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

 

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

TypeScript

 

Generalizing the Solution

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

TypeScript

 

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

 

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

TypeScript

 

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

 

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

 

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!

Source:
https://dzone.com/articles/branded-types-in-typescript