Course contentsShow
← TypeScript
Lesson 1354 of 1,79631. Type-Driven DesignFree lesson

Multiple Brands on One Type

Combining multiple brand intersections to create types with layered constraints like ValidatedSortedArray.

Multiple Brands on One Type

What you'll learn: How to layer multiple brand intersections onto a single type to enforce compound constraints that each represent different validation rules.


The Concept

You've learned how to create a single brand to distinguish, say, ValidatedEmail from plain string. But what if a value must satisfy multiple independent constraints? For instance, an array that's both validated and sorted, or a user ID that's both verified and encrypted.

Multiple brands let you stack these constraints using intersection types. Each brand documents a specific guarantee about the value, and the type system ensures you can't use a value until all required validations have occurred.

How It Works

Combine brands with &:

declare const __validated: unique symbol;
declare const __sorted: unique symbol;

type Validated<T> = T & { readonly [__validated]: true };
type Sorted<T> = T & { readonly [__sorted]: true };

type ValidatedSortedArray<T> = Validated<Sorted<T[]>>;

Now ValidatedSortedArray<number> carries two invisible markers. You can only construct it by passing through smart constructors that validate and sort:

function createValidatedSortedArray<T>(
  input: T[],
  isValid: (arr: T[]) => boolean
): ValidatedSortedArray<T> | null {
  if (!isValid(input)) return null;
  
  const sorted = [...input].sort();
  return sorted as ValidatedSortedArray<T>;
}

Both brands must be present before the value is considered fully processed. You can write functions that require one, the other, or both:

function processValidated<T>(arr: Validated<T[]>) { /* ... */ }
function processSorted<T>(arr: Sorted<T[]>) { /* ... */ }
function processFullyReady<T>(arr: ValidatedSortedArray<T>) { /* ... */ }

This expresses layered requirements explicitly in the type signature, preventing misuse at compile time.

Key Takeaway: Multiple brands compose via intersection types to represent compound constraints like ValidatedSortedArray, ensuring each independent validation step is reflected in the type system.