Matt Pocock Profile picture
I teach devs for a living. Author of Total TypeScript and AI Hero. Ex-@vercel. Used to be a voice coach.

Feb 13, 2023, 13 tweets

Let's talk about branded types.

If I were building an app where security was critical, I'd use the crap out of them.

A Brand type lets you use a bit of 'nominal' typing inside TypeScript.

By declaring a unique symbol, 'brand', we can use this Brand type helper to create types with 'names'.

For instance, these two types are still strings, but they're now 'named' Password and Email.

You can't pass a normal string to a slot that expects a password...

You'd need to 'cast' it to be a password...

Or, create a type predicate function that validates that it's a valid password.

This 'type predicate' approach is super nice, because you can take in the un-branded input and get out the branded output.

You can see that, inside the if statement where we check it's valid, the password IS valid:

But outside it, it's just a regular string.

Branded types are extremely powerful for security-critical systems, like finance apps, which require a lot of validations and checks before actions can be performed.

For instance, what's wrong with this picture?

That's right - makePayment can be called using _any_ user, whether they've been validated or not.

Using a branded user, you can ensure that makePayment only ever gets called with a user that has already been validated.

Of course, you'll have unit tests covering this behaviour.

But layering your types on top will give you a whole extra level of security and peace of mind, as well as documenting exactly where validation checks are performed.

I thought branded types were so useful that I made a whole section about them in Total TypeScript, my comprehensive TS course.

It's in the 'Advanced TypeScript Patterns' workshop, along with classes, type predicates, globals and working with libraries.

totaltypescript.com/workshops/adva…

If you dug this thread, then give the original tweet an RT and let's spread TS awesomeness to more folks.

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling