Sub topic 7
Branding numbers: units and constrained values
Assume you know TypeScript type aliases, generics, intersection types, and the difference between compile-time types and runtime values. This chapter uses a reusable Brand<T, B> helper. A branded number is still a JavaScript number at runtime, but TypeScript treats its brand as a separate type.
Preventing unit mix-ups
A plain number cannot express whether a value represents meters, seconds, dollars, or a temperature. Separate aliases do not solve the problem:
type Meters = number;
type Seconds = number;
function travel(distance: Meters, time: Seconds): number {
return distance / time;
}
const distance: Meters = 100;
const time: Seconds = 5;
travel(time, distance); // Compiles, even though the arguments are reversedTypeScript compares these aliases by their structure. Both structures are just number.
A brand adds a compile-time-only property:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brand]: B;
};
type Meters = Brand<number, "Meters">;
type Seconds = Brand<number, "Seconds">;The unique symbol key avoids collisions with ordinary object properties. The brand does not add data to the number. It only makes Meters and Seconds incompatible during type checking.
Constructing and using branded numbers
A constructor is a function that checks or intentionally creates a branded value. Keep casts inside these functions rather than spreading them through application code.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brand]: B;
};
type Meters = Brand<number, "Meters">;
type Seconds = Brand<number, "Seconds">;
function meters(value: number): Meters {
if (!Number.isFinite(value) || value < 0) {
throw new RangeError("Meters must be a finite, non-negative number");
}
return value as Meters;
}
function seconds(value: number): Seconds {
if (!Number.isFinite(value) || value < 0) {
throw new RangeError("Seconds must be a finite, non-negative number");
}
return value as Seconds;
}
function speed(distance: Meters, duration: Seconds): number {
return distance / duration;
}
const distance = meters(100);
const duration = seconds(5);
console.log(speed(distance, duration)); // 20
// speed(duration, distance); // Error: Seconds is not assignable to MetersThe runtime checks reject invalid values. The brand prevents the wrong unit from reaching a function when the value has already been validated.
Arithmetic removes the brand
Arithmetic produces a plain number, because TypeScript cannot know whether the operation preserves the meaning of a brand.
function addMeters(a: Meters, b: Meters): Meters {
return meters(a + b);
}
const total = addMeters(meters(5), meters(3)); // Meters
const rawTotal = distance + meters(20); // numberUse a constructor such as meters to re-establish the brand. Prefer this approach over a direct cast because the constructor remains the place where runtime rules are enforced.
Constrained values
Brands also represent rules about one kind of number. For example, a positive integer can be used for an array index, retry count, or repetition count.
type PositiveInt = Brand<number, "PositiveInt">;
function positiveInt(value: number): PositiveInt {
if (!Number.isInteger(value) || value <= 0) {
throw new RangeError(`Expected a positive integer, got ${value}`);
}
return value as PositiveInt;
}
function repeat(times: PositiveInt, text: string): string {
return text.repeat(times);
}
console.log(repeat(positiveInt(3), "go")); // gogogoA branded number does not automatically preserve its constraint after arithmetic. For example, positiveInt(2) - 3 is a plain number and may be negative. Validate the result before branding it again.
A boundary-to-function model
Use branded units when confusing two numeric meanings would cause a real defect, especially in APIs that accept several values with the same primitive type.
Exercise
Why does const result = meters(5) + meters(3) have type number instead of Meters, and how should you obtain a Meters value from it?
Show answer
Arithmetic returns a plain number. Pass the result through the validating meters constructor, as in const result = meters(meters(5) + meters(3)).