Branded Types for Validated Primitives
Combine runtime parsers with branded TypeScript types so validated emails, user IDs and slugs cannot be mixed up by accident.
Code
declare const brand: unique symbol;
export type Brand<Value, Name extends string> = Value & { readonly [brand]: Name };
export type Email = Brand<string, "Email">;
export type UserId = Brand<string, "UserId">;
export type Slug = Brand<string, "Slug">;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const USER_ID_PATTERN = /^usr_[a-z0-9]{8,}$/;
const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export function parseEmail(value: string): Email {
if (typeof value !== "string") throw new TypeError("email must be a string");
const normalized = value.trim().toLowerCase();
if (normalized.length > 254 || !EMAIL_PATTERN.test(normalized)) {
throw new Error(`invalid email address "${value}"`);
}
return normalized as Email;
}
export function parseUserId(value: string): UserId {
if (typeof value !== "string") throw new TypeError("user id must be a string");
const normalized = value.trim();
if (!USER_ID_PATTERN.test(normalized)) throw new Error(`invalid user id "${value}"`);
return normalized as UserId;
}
export function parseSlug(value: string): Slug {
if (typeof value !== "string") throw new TypeError("slug must be a string");
const normalized = value.trim().toLowerCase();
if (normalized.length === 0 || normalized.length > 80 || !SLUG_PATTERN.test(normalized)) {
throw new Error(`invalid slug "${value}"`);
}
return normalized as Slug;
}
export function isEmail(value: string): value is Email {
return value.length <= 254 && EMAIL_PATTERN.test(value.trim().toLowerCase());
}
function sendWelcome(email: Email, userId: UserId): string {
return `queued welcome for ${userId} at ${email}`;
}
const email = parseEmail(" Ada@Example.COM ");
const userId = parseUserId("usr_1234abcd");
console.log(email, userId);
console.log(isEmail("not-an-email"));
console.log(sendWelcome(email, userId));
console.log(parseSlug("release-notes-2026"));Output
Captured from a sandboxed run of this snippet in the build pipeline.
ada@example.com usr_1234abcd
false
queued welcome for usr_1234abcd at ada@example.com
release-notes-2026What the code does
Branded Types for Validated Primitives is built around the functions parseEmail, parseUserId, parseSlug and isEmail.
TypeError and Error is the guard’s signal — thrown at the branch, before any partial work happens.
Watch out for
- The guard
typeof value !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
Signature: export function parseEmail(value: string)
The surface worth importing is parseEmail; the helpers around it are private to the snippet.
Statements that matter
if (!USER_ID_PATTERN.test(normalized)) throw new Error(`invalid user id "${value}"`);
if (typeof value !== "string") throw new TypeError("user id must be a string");
if (typeof value !== "string") throw new TypeError("email must be a string");
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What happens on invalid input?
- The code refuses to continue: `TypeError` and `Error` is thrown while the state is still recoverable.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `parseEmail`, `parseUserId`, `parseSlug` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.