Branding nominal types

Contents
Structural collisions
Brand with a tag
Use branded ids
Escape hatch

Structural collisions

TypeScript compares object shapes, not names, so two string ids look identical to the checker. A user id can flow into an order id slot with no warning at all.

The bug surfaces far from its cause: a mistyped argument fetches the wrong record. Branding gives each id a distinct type while keeping strings at runtime.

function loadOrder(id: string): string { return "order:" + id; } const userId = "user-7"; loadOrder(userId);

Brand with a tag

A brand is an extra phantom field intersected with a plain type. It exists only for checking, never at runtime, yet it makes two string aliases incompatible.

Name the brand after the concept it protects. Clear brand names turn idle strings into documented domain values across the whole file.

type UserId = string & { readonly brand: "UserId" }; type OrderId = string & { readonly brand: "OrderId" };

Use branded ids

Constructors validate raw text once and return the branded result. After that point every function can demand the exact brand and reject lookalike strings.

Push validation to the edges: parse at input, then enjoy precise types inside. The middle layers stay short because wrong ids no longer compile.

function makeUserId(raw: string): UserId { if (raw.length === 0) { throw new Error("Empty user id"); } return raw as UserId; } function greetUser(id: UserId): string { return "hi " + id; }

Escape hatch

Sometimes you must drop back to a plain string, for example to build a URL or write a log line. A tiny helper converts a branded id to its raw text in one visible step.

Keep escapes rare and explicit at boundaries. If raw text leaks everywhere, the brand loses value and mixups return through the back door.

function rawId(id: UserId): string { return id as string; } console.log(rawId(makeUserId("user-7")));

Next: Result types

Article author: Arthur Isaev

Related articles
TypeScript
TypeScript course: zero to hero in 100 lessons
What is TypeScript and where it runs
Install TypeScript
Your first program
tsconfig.json
Basic types
any, unknown, never
Arrays and tuples
Type aliases
Interfaces
Unions and literals
Function types
Parameters
Overloads
Generics
Constraints
Return types
Arrow functions
Callbacks
Narrowing
Assertions
Classes
Constructors
Modifiers
implements
Abstract classes
static
Getters and setters
Enums
ES modules
Decorators
Discriminated unions
Intersections
Mapped types
Conditional types
infer
Template literal types
keyof and typeof
Utility types
satisfies
const assertions
tsc CLI
tsconfig deep dive
Strict mode
Source maps
Declaration files
Linting
Formatting
Debugging
Project references
Publishing packages
Run with Node
npm scripts
argv and env
Files with fs
path and os
JSON IO
Dates
Crypto random
Timers
process
Callbacks to promises
Promises
async and await
Promise.all
Promise.race
HTTPS client
Abort and timeouts
Async error handling
Sequential vs parallel
Event loop
Tests with assert
Test layout
Fixtures
Test doubles
CI tests
DOM basics
DOM events
Fetch in browsers
Forms
Web storage
Npm packages
Bundling concept
SPA concepts
Typed API client
Hand-rolled validation
Iterators and generators
Mixins
Branding nominal types
Result types
Options objects
Builder
Event emitters
Streams
Workers
Deserialization
Capstone: todo CLI
Capstone: JSON API
Capstone: utils library
Modern TypeScript tour
Hero roadmap: the whole course on one page
Install TypeScript on Windows 11
Install TypeScript on Ubuntu
Install TypeScript on Rocky Linux
Install TypeScript on macOS
Install TypeScript on FreeBSD
TypeScript in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: