Create nominal types in TypeScript
Quick Answer
Branded types add a phantom type tag to a primitive so TypeScript treats two structurally identical values as distinct types, preventing accidental mixing.
1type Brand<K, T> = K & { __brand: T };
2
3type UserId = Brand<string, 'UserId'>;
4type Email = Brand<string, 'Email'>;
5
6const UserId = (id: string): UserId => id as UserId;
7const Email = (email: string): Email => email as Email;
8
9// Usage - prevents mixing different branded types
10const userId = UserId('123');
11const email = Email('user@example.com');TypeScript uses structural typing, which means two types with the same shape are interchangeable. Branded types add a phantom type tag to primitive values so the compiler treats them as distinct types even though they have the same underlying representation. This prevents bugs like passing a UserId where an Email is expected.
Yes. The `__brand` property only exists in the TypeScript type system. It is never present in the compiled JavaScript output, so there is zero runtime overhead.
This free typescript code snippet for branded types is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this advanced-level example will help you implement branded types quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.