Course contentsShow
← TypeScript
Lesson 658 of 1,79615. Generic ConstraintsFree lesson

Branded Type Constraints

Use branded types as constraints to ensure type parameters carry specific compile-time metadata or tags.

Branded Type Constraints

You'll learn how to use branded types as generic constraints to enforce compile-time metadata or tags on type parameters.

What Are Branded Type Constraints?

A branded type is a type that carries a compile-time "tag" or "brand" to distinguish it from other structurally identical types. When you use a branded type as a constraint in a generic, you force the type parameter to carry that specific brand — ensuring only properly tagged values pass through.

Think of it like airport security checkpoints: even if two passengers look identical, only those with the correct stamp in their passport (the brand) can board certain flights (satisfy the constraint).

Core Idea

You combine branded types with the extends keyword in generic constraints. This ensures that generic functions or types only accept values that have been explicitly branded with specific metadata:

type UserId = number & { readonly __brand: "UserId" };
type ProductId = number & { readonly __brand: "ProductId" };

function getUser<T extends UserId>(id: T): void {
  // T must be branded as UserId
  console.log(`Fetching user: ${id}`);
}

declare const userId: UserId;
declare const productId: ProductId;

getUser(userId);      // ✓ Works
getUser(productId);   // ✗ Error: ProductId doesn't extend UserId
getUser(42);          // ✗ Error: number doesn't extend UserId

The constraint T extends UserId means TypeScript won't let you pass regular numbers or differently-branded types — only values tagged as UserId satisfy the constraint.

Why This Matters

Branded type constraints prevent accidental mixing of semantically different values that happen to share the same runtime type. The brand serves as compile-time documentation that follows your type parameters everywhere.

Key Takeaway: Use branded types as constraints to ensure generic type parameters carry specific compile-time tags, preventing semantically incorrect values from satisfying the constraint.