Sub topic 2
Creating Branded Values Safely with Smart Constructors
Assume you know TypeScript type aliases, generics, intersections, and the difference between compile-time types and runtime values. A brand prevents accidental mixing at compile time, but it does not validate data by itself. Create branded values only after checking them at runtime.
Smart constructors
A smart constructor is a function that validates ordinary input and returns a branded value. The cast stays inside this function, where the validation justifies it.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brand]: B;
};
type Email = Brand<string, "Email">;
function parseEmail(value: unknown): Email {
if (
typeof value !== "string" ||
!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)
) {
throw new Error("Invalid email address");
}
return value as Email;
}
function sendNewsletter(to: Email): void {
console.log(`Sending newsletter to ${to}`);
}
const email = parseEmail("[email protected]");
sendNewsletter(email);A caller cannot create an Email from an arbitrary string without using a cast. The constructor provides one controlled entry point.
Type predicates and assertion functions
A type predicate has the form value is SomeType. If it returns true, TypeScript narrows the value to that type.
function isEmail(value: string): value is Email {
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value);
}
function printEmail(value: string): void {
if (isEmail(value)) {
sendNewsletter(value);
}
}An assertion function throws when validation fails. After it returns, TypeScript trusts the narrowed type.
type PositiveInt = Brand<number, "PositiveInt">;
function assertPositiveInt(
value: number
): asserts value is PositiveInt {
if (!Number.isInteger(value) || value <= 0) {
throw new RangeError("Expected a positive integer");
}
}Branded numbers and units
Brands also prevent unit mistakes. Arithmetic usually produces a plain number, so revalidate or re-brand the result at a controlled point.
type Meters = Brand<number, "Meters">;
type Seconds = Brand<number, "Seconds">;
const meters = (value: number): Meters => value as Meters;
const seconds = (value: number): Seconds => value as Seconds;
function addMeters(a: Meters, b: Meters): Meters {
return meters(a + b);
}
addMeters(meters(5), meters(3));
// addMeters(meters(5), seconds(2)); // compile-time errorValidate at program boundaries
Parse HTTP bodies, configuration, database results, and JSON before they enter trusted application code.
Keep casts inside boundary parsers and smart constructors. Do not cast raw JSON directly to a brand.
Exercise
Why should as Email usually appear only inside a parser or constructor?
Show answer
The cast bypasses runtime checks, so keeping it inside validated code prevents invalid values from entering trusted code.