Sub topic 7
Branding Numbers: Units and Constrained Values
Earlier chapters branded strings such as UserId and Email. Numbers have the same problem, and it is often more costly. A function that takes "a number" can't tell meters from seconds, or a valid port from -3. This chapter applies the brand pattern to numbers in two ways: to units (what the number measures) and to constraints (which numbers are allowed).
What this chapter assumes
You should know the generic Brand<T, B> helper from the previous chapters. You should also know that brands exist only at compile time, and that a smart constructor is a function that validates a value before returning it as a branded type. Everything below reuses this helper:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };Why numbers need brands
A plain number says nothing about meaning. Consider this signature:
function braking(distance: number, speed: number): number {
return (speed * speed) / (2 * distance);
}A caller can swap the arguments, pass feet where meters are expected, or pass NaN, and the compiler accepts all of it. The Mars Climate Orbiter was lost in 1999 partly because one team's software produced pound-force seconds where another team's software expected newton seconds. Branding turns this class of mix-up into a compile error.
Numbers have a second problem that strings share less often. Many numbers are only valid in a range. A port is an integer from 0 to 65535. A quantity in a shopping cart is a positive integer. number also includes NaN, Infinity, and fractions, which are rarely what you mean.
Brands for units
A unit brand tags a number with what it measures:
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">;
const meters = (n: number): Meters => n as Meters;
const seconds = (n: number): Seconds => n as Seconds;
function addMeters(a: Meters, b: Meters): Meters {
return (a + b) as Meters;
}
addMeters(meters(5), meters(3));
addMeters(meters(5), seconds(2)); // Error: Seconds is not assignable to MetersThe meters and seconds helpers are the only places that cast. Every other part of the program receives a value that already carries its unit.
A branded number is still a number at runtime and for most operations. You can pass a Meters to Math.round, toFixed, or console.log without any conversion. The brand only restricts where a plain number can flow in, not where a branded one can flow out.
Converting between units
Different units of the same quantity should get different brands, and the only way from one to the other should be a conversion function:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Meters = Brand<number, "Meters">;
type Feet = Brand<number, "Feet">;
const meters = (n: number): Meters => n as Meters;
const feet = (n: number): Feet => n as Feet;
const FEET_PER_METER = 3.28084;
function metersToFeet(m: Meters): Feet {
return feet(m * FEET_PER_METER);
}
function feetToMeters(f: Feet): Meters {
return meters(f / FEET_PER_METER);
}
const runway = meters(1200);
console.log(metersToFeet(runway)); // about 3937 feet
// feetToMeters(runway); // Error: Meters is not assignable to FeetNow a value in feet can't reach code that expects meters unless someone calls the conversion. The conversion factor lives in one function, so it can be reviewed once.
Arithmetic returns a plain number
The most common surprise with branded numbers is arithmetic. The operators +, -, *, and / accept any number-like operands and produce a plain number. The brand is lost:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Meters = Brand<number, "Meters">;
type Feet = Brand<number, "Feet">;
declare const m: Meters;
declare const f: Feet;
const sum: Meters = m + m; // Error: number is not assignable to Meters
const nonsense = m + f; // compiles: both operands are numbers, the result is numberTwo consequences follow.
- You must re-brand results, usually inside a small function such as
addMetersthat owns the cast. This keeps the casts out of business logic. - The compiler does not stop
m + f. TypeScript checks the+operator againstnumber, and both operands qualify. Brands protect function arguments, assignments, and returns, but they don't protect operators.
If a codebase does a lot of unit arithmetic, write a small set of typed helpers (addMeters, scaleMeters) and use them consistently. Code review or a lint rule has to cover direct operator use.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Meters = Brand<number, "Meters">;
const meters = (n: number): Meters => n as Meters;
function scaleMeters(m: Meters, factor: number): Meters {
return meters(m * factor);
}
function longest(a: Meters, b: Meters): Meters {
return a >= b ? a : b; // comparison and selection keep the brand
}Comparison operators and the conditional expression keep the brand, because longest returns one of its original arguments. Math.max(a, b) would return a plain number.
Constrained values
Units say what a number means. Constraints say which numbers are legal. A constrained brand is created only by a function that checks the constraint, so holding the brand is proof that the check ran.
A type predicate and a constructor
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type PositiveInt = Brand<number, "PositiveInt">;
function isPositiveInt(n: number): n is PositiveInt {
return Number.isInteger(n) && n > 0;
}
function toPositiveInt(n: number): PositiveInt {
if (!isPositiveInt(n)) {
throw new RangeError(`Expected a positive integer, got ${n}`);
}
return n; // narrowed to PositiveInt by the guard above
}
function repeat(times: PositiveInt, text: string): string {
return text.repeat(times);
}
console.log(repeat(toPositiveInt(3), "ab")); // ababab
// repeat(3, "ab"); // Error: number is not assignable to PositiveIntNumber.isInteger already rejects NaN, Infinity, and fractions, so the extra n > 0 is the only rule you add.
Returning `undefined` instead of throwing
Throwing suits values that should always be valid. When invalid input is expected, such as user-provided data, return a result the caller must handle:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Port = Brand<number, "Port">;
function parsePort(n: number): Port | undefined {
return Number.isInteger(n) && n >= 0 && n <= 65535 ? (n as Port) : undefined;
}
function listen(port: Port): void {
console.log(`listening on ${port}`);
}
const port = parsePort(8080);
if (port !== undefined) {
listen(port);
}The return type Port | undefined forces the caller to check before using the value, and listen never has to validate again.
Money as integer cents
Floating-point numbers can't represent most decimal fractions exactly. A common design stores money as an integer count of the smallest unit and brands it:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Cents = Brand<number, "Cents">;
function cents(n: number): Cents {
if (!Number.isSafeInteger(n)) {
throw new RangeError(`Cents must be a safe integer, got ${n}`);
}
return n as Cents;
}
function addCents(a: Cents, b: Cents): Cents {
return cents(a + b);
}
console.log(addCents(cents(1999), cents(1)));addCents calls the validating constructor on the result instead of casting. If the sum leaves the safe integer range, the error surfaces at the operation that caused it.
How a number moves through branded code
Pitfalls specific to numbers
- Operators are unchecked. As shown above,
meters + feetcompiles. Route arithmetic through helper functions. - Constraints decay after arithmetic.
PositiveInt - PositiveIntcan be zero or negative, but the type system returnsnumber, so you can't accidentally treat it as positive. Re-validate the result. - Casts skip the check.
5 as PositiveIntcompiles and-5 as PositiveIntdoes too. Keep casts inside the constructors. - Literal numbers need a constructor.
const n: Meters = 5is an error. This is intended, but it makes tests and fixtures slightly more verbose. - Floating-point rounding. A brand on a
numberdoesn't fix precision. Converting between feet and meters gives approximate values, so compare with a tolerance. - JSON and runtime data.
JSON.parsereturnsany, so a branded field read from JSON is unchecked until you validate it. The next chapters cover this at system boundaries.
When number brands pay off
| Situation | Brand worth it? |
|---|---|
| Several quantities share a signature (distance, time, speed) | Yes |
| Two units of the same quantity exist in the code (meters and feet) | Yes |
| A value has a hard validity rule used in many places (port, quantity) | Yes |
| A single local variable used in one function | No |
| Heavy numeric code with many operators in tight loops | Often no, since every result needs a re-brand |
Exercise
Given type Seconds = Brand<number, "Seconds">, a developer writes "function total(a: Seconds, b: Seconds): Seconds { return a + b; }" and gets a compile error. Why does it fail, and how do you fix it without moving the cast to the call sites?
Show answer
The + operator returns a plain number, and number is not assignable to Seconds because the brand property is missing. Fix it inside the function by re-branding the result: return (a + b) as Seconds, or better, call a validating constructor such as seconds(a + b). Callers keep passing and receiving Seconds and never cast.
Exercise
Write the signature and the check for a smart constructor parsePercentage that accepts a number and returns a branded Percentage, or undefined, for values from 0 to 100 inclusive. Which built-in call should the check use to reject NaN and Infinity?
Show answer
The signature is function parsePercentage(n: number): Percentage | undefined, where type Percentage = Brand<number, "Percentage">. The body returns n as Percentage when Number.isFinite(n) && n >= 0 && n <= 100, and undefined otherwise. Number.isFinite rejects NaN and both infinities. Comparisons with NaN are always false, so the range check also rejects NaN, but the explicit isFinite call makes the intent clear.