Sub topic 9
Flavored types: brands without the cast
This chapter assumes you know the generic Brand<T, B> helper from the earlier chapters and understand intersection types and unique symbol. It covers a lighter variant of branding called flavoring. You will learn how it works, what it allows and what it blocks, and how to decide between it and a strict brand.
The cost of strict brands
A strict brand forces every value to come through a constructor or a cast:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type CustomerId = Brand<string, "CustomerId">;
function loadCustomer(id: CustomerId): void {
console.log("loading", id);
}
const raw: string = "c_1";
// loadCustomer(raw); // Error: string is not assignable to CustomerId
loadCustomer(raw as CustomerId); // compiles only because of the castThat friction is the point when the value needs validation, such as an email address. It is a nuisance when the value is a plain identifier you generated yourself, or one that arrives from a database layer you trust. In a large codebase you may end up with hundreds of as CustomerId casts. Each cast is a place where a mistake can hide, and each one makes the code noisier.
Flavoring removes the cast for the common case. It still stops you from mixing up two different kinds of ID.
How a flavor works
A flavor is a brand whose tag property is optional:
declare const flavor: unique symbol;
type Flavor<T, F extends string> = T & { readonly [flavor]?: F };
type CustomerId = Flavor<string, "CustomerId">;
type ProductId = Flavor<string, "ProductId">;
const raw: string = "c_1";
const customerId: CustomerId = raw; // allowed: no cast needed
const productId: ProductId = customerId; // Error: the flavors differThe only difference from Brand is the ? after the property key. It has two effects.
- A plain
stringis assignable toCustomerId. A string has no[flavor]property, and an optional property may be absent, so the assignment is valid. - A
CustomerIdis not assignable toProductId. When the property is present, its type is checked. The type"CustomerId" | undefineddoes not fit"ProductId" | undefined.
Nothing exists at runtime, as with any brand. The flavor symbol is declared with declare const, so it emits no JavaScript.
Why the property is optional
Remember how assignability works. For a target type with a property, the source must have a compatible property. If the property is required, a plain string fails the check because it lacks the property. If the property is optional, the check passes when the property is missing. If the property is present, its type must match.
So the optional tag creates a one-way door. Untagged values may enter a flavored type. Differently tagged values may not.
Because the diagram fence must be written in the required form, here it is:
What flavors catch and what they let through
Take a function that accepts a flavored ID.
declare const flavor: unique symbol;
type Flavor<T, F extends string> = T & { readonly [flavor]?: F };
type CustomerId = Flavor<string, "CustomerId">;
type ProductId = Flavor<string, "ProductId">;
function loadCustomer(id: CustomerId): void {
console.log("loading customer", id);
}
function loadProduct(id: ProductId): void {
console.log("loading product", id);
}
const customerId: CustomerId = "c_1";
const productId: ProductId = "p_9";
loadCustomer(customerId); // OK
loadCustomer("c_2"); // OK: a plain string literal is accepted
loadProduct(customerId); // Error: CustomerId is not assignable to ProductId
loadCustomer(productId); // Error: ProductId is not assignable to CustomerIdThe last two lines show the benefit. Once a value has been given a flavor, such as the return type of a function or a typed field, the compiler tracks it and rejects mix-ups. This is the mistake that plain string aliases cannot catch.
The second call shows the trade-off. loadCustomer("c_2") compiles, and so does any untagged string. A flavor therefore cannot guarantee that a value is a valid customer ID. It guarantees only that a value known to be some other kind of ID does not get used as a customer ID.
A realistic failure
The weakness appears where untyped strings enter your program:
declare const flavor: unique symbol;
type Flavor<T, F extends string> = T & { readonly [flavor]?: F };
type CustomerId = Flavor<string, "CustomerId">;
type ProductId = Flavor<string, "ProductId">;
declare function loadCustomer(id: CustomerId): void;
declare function productIdFromUrl(url: string): string;
const fromUrl = productIdFromUrl("/products/p_9");
loadCustomer(fromUrl); // compiles, even though this is a product IDproductIdFromUrl returns plain string, so the compiler has no information to reject the call. If the function were declared to return ProductId, the call would fail. A flavor protects you only as far as the flavor is applied. Every function that returns an ID needs a flavored return type, or the protection has gaps.
Strict brand versus flavor
| Property | Strict brand | Flavor |
|---|---|---|
| Tag property | Required | Optional |
| Plain `string` assignable to it | No, needs a cast or constructor | Yes |
| Different tags assignable to each other | No | No |
| Guarantees a value was validated | Yes, if casts are confined to constructors | No |
| Noise at call sites | Higher | Lower |
| Best for | Validated data: emails, positive integers, sanitized HTML | Identifiers and labels where mix-ups are the risk |
The deciding question is whether the type carries a rule. A PositiveInt means "this number was checked". If untagged numbers can flow in, the type promises nothing, so use a strict brand. A CustomerId that your own code created and nobody validates further is mostly about keeping categories apart. A flavor gives you that at much lower cost.
Mixing flavors and brands
You can use both in one codebase, and a common split is:
- Flavors for identifiers (
UserId,OrderId,ProductId). - Strict brands for values with invariants (
Email,PositiveInt,Url).
Both can share one helper file:
declare const brand: unique symbol;
declare const flavor: unique symbol;
export type Brand<T, B extends string> = T & { readonly [brand]: B };
export type Flavor<T, F extends string> = T & { readonly [flavor]?: F };
export type UserId = Flavor<string, "UserId">;
export type Email = Brand<string, "Email">;
export function parseEmail(value: string): Email {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
throw new Error(`Invalid email: ${value}`);
}
return value as Email;
}
export function sendWelcome(to: Email, userId: UserId): void {
console.log("welcome", to, "for", userId);
}
const id: UserId = "u_1";
sendWelcome(parseEmail("[email protected]"), id); // OK
// sendWelcome("[email protected]", id); // Error: string is not assignable to EmailKeeping the brand and flavor symbols separate matters. If both helpers used the same key, a Brand and a Flavor with the same tag would collide in confusing ways. Separate symbols keep the two techniques independent.
Edge cases to know
- Flavors flow outward freely. A
CustomerIdis assignable tostring, so passing it toconsole.log, string methods, or any function expectingstringworks. Strict brands behave the same way. - Two flavors of different base types stay apart.
Flavor<string, "X">andFlavor<number, "X">are different types because the base types differ. - Flavors do not stack automatically. With a single optional tag key, intersecting two flavors such as
Flavor<Flavor<string, "A">, "B">produces a tag of type"A" & "B", which reduces tonever. For layered refinement, use the object-keyedBrandform from the composition chapter. - Object types can slip through. An object literal with no
[flavor]key is fine, but an object whose type declares an incompatible tag is rejected. This is rarely an issue for primitives. - Optional properties and
exactOptionalPropertyTypes. With that compiler flag on,[flavor]?: Fdoes not acceptundefinedas an explicit value. The flag does not change how plain strings are assigned, so the flavor still works.
Exercise
Given type A = Flavor<string, "A"> and type B = Flavor<string, "B">, which of these lines compile? (1) const a: A = "x"; (2) const b: B = a; (3) const s: string = a; Explain each.
Show answer
Lines 1 and 3 compile. Line 1 works because a plain string has no [flavor] property, and an optional property may be absent. Line 3 works because A is string & {...}, which is assignable to string. Line 2 fails because a carries the tag type "A", which is not assignable to "B".
Exercise
A function makeOrderId(): string is used to create IDs that are passed to loadOrder(id: OrderId), where OrderId is a flavor. Mix-ups with UserId are still not caught for values returned by makeOrderId. Why, and what is the fix?
Show answer
makeOrderId returns plain string, so the compiler cannot tell which kind of ID it produced, and that value is assignable to any flavor. The fix is to change the return type to OrderId, so the flavor follows the value through the program.