Sub topic 5
Creating Branded Values Safely with Smart Constructors
This chapter assumes you know TypeScript type aliases, generics, intersection types, and the difference between compile-time types and runtime values.
A branded type prevents unrelated values with the same underlying shape from being mixed. However, TypeScript cannot verify that a string is a valid email address or that a number is positive. A smart constructor is a function that checks a value at runtime and returns the branded type only when the check succeeds.
Keep the Brand Private
A reusable brand helper adds a type-only property keyed by a unique symbol. The symbol does not appear in the JavaScript output.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brand]: B;
};
type Email = Brand<string, "Email">;Email is still usable wherever a string is expected, but an ordinary string is not assignable to Email. This prevents callers from creating an email value without going through a validation step.
The constructor is the only place that needs a type assertion:
function parseEmail(value: string): Email {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
throw new Error(`Invalid email address: ${value}`);
}
return value as Email;
}
function sendReceipt(to: Email): void {
console.log(`Sending receipt to ${to}`);
}
const email = parseEmail("[email protected]");
sendReceipt(email);
try {
parseEmail("not-an-email");
} catch (error) {
console.log("Rejected invalid input");
}The assertion is safe here because the function checks the value immediately before returning it. Callers receive a guarantee: every Email produced by parseEmail passed this validation.
Returning an Error Instead of Throwing
Throwing is useful when invalid input is exceptional. For user input or external data, returning a result can make failure explicit.
type ParseEmailResult =
| { ok: true; value: Email }
| { ok: false; error: string };
function tryParseEmail(value: string): ParseEmailResult {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
return { ok: false, error: "The email address is invalid" };
}
return { ok: true, value: value as Email };
}
const result = tryParseEmail("[email protected]");
if (result.ok) {
sendReceipt(result.value);
} else {
console.log(result.error);
}The successful branch contains a branded Email. The failed branch contains a message and no branded value. This design makes it harder to accidentally continue with invalid data.
Where Smart Constructors Belong
Use smart constructors at boundaries where data enters your trusted application:
- HTTP request bodies
- Environment variables
- Configuration files
- Database rows
- Command-line arguments
- Parsed JSON
After validation, pass branded values through internal functions. Those functions no longer need to repeat the same checks.
Avoid Trusting Assertions
This assertion compiles but defeats the purpose of branding:
const unsafe = "not-an-email" as Email;TypeScript accepts the assertion without running a validator. Treat assertions as an escape hatch for code you control, not as a validation mechanism.
A good rule is to expose constructors such as parseEmail or tryParseEmail, keep the brand declaration private to the module, and avoid exporting arbitrary casting helpers. This makes the valid creation path clear and reviewable.
Exercise
Why should the assertion value as Email be kept inside parseEmail instead of used by every caller?
Show answer
The constructor performs the runtime validation first. Keeping the assertion there ensures callers receive an Email only through a checked creation path.