Sub topic 2
The problem with plain string and number aliases
This chapter assumes you know TypeScript type aliases, function signatures, and the idea that types exist only at compile time. The previous chapter showed that TypeScript compares types by shape. Here you will see what that rule does to code that models IDs, units, and other values that share a primitive type.
What an alias gives you
A type alias gives an existing type a new name. It does not create a new type. This line makes UserId and string the same type:
type UserId = string;Everywhere TypeScript expects a UserId, it accepts any string. Everywhere it expects a string, it accepts a UserId. The alias adds a name for readers and nothing else.
The compiler checks assignability by comparing the underlying types. The alias name may still appear in hover text and in some error messages, which makes it look like a distinct type. It is not distinct.
Two aliases of the same type
Suppose a codebase defines these aliases to keep its signatures readable:
type UserId = string;
type OrderId = string;
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId: UserId = "u_123";
loadOrder(userId); // compiles: both aliases are just stringThe programmer wrote OrderId to say "this function wants an order ID". The compiler records only that the parameter is a string. The call passes a user ID and compiles without complaint.
Where the mix-ups happen
This problem has a name: primitive obsession. It means using bare primitives such as string and number for values that have different meanings and different rules. The compiler cannot help you, because every one of those values has the same type.
The bugs below compile cleanly. Most are silent. Nothing throws, and the program keeps running with wrong data.
Swapped arguments
Functions with several parameters of the same primitive type are the most common source:
type UserId = string;
type OrderId = string;
function cancelOrder(userId: UserId, orderId: OrderId): string {
return `user ${userId} cancelled order ${orderId}`;
}
const userId: UserId = "u_123";
const orderId: OrderId = "o_456";
// Arguments are in the wrong order, and this still compiles.
console.log(cancelOrder(orderId, userId));The output reads "user o456 cancelled order u123". In real code, that call might delete the wrong record or write an audit log that points at the wrong entity. Code review catches this only if the reviewer checks every call site by eye.
Lookups with the wrong key
Collections keyed by a primitive have the same weakness. Map<UserId, User> is really Map<string, User>:
type UserId = string;
type OrderId = string;
interface User {
name: string;
}
const users = new Map<UserId, User>([["u_123", { name: "Ada" }]]);
const orderId: OrderId = "o_456";
const user = users.get(orderId); // compiles
console.log(user?.name); // undefinedThe result type is User | undefined, so the compiler is satisfied. The lookup can never succeed, because order IDs are never user IDs. You find out only when the program misbehaves.
Numbers with different units
Numbers have the same problem, and the consequences can be more serious because a wrong number often looks plausible:
type Meters = number;
type Seconds = number;
function averageSpeed(distance: Meters, time: Seconds): number {
return distance / time;
}
const distance: Meters = 100;
const time: Seconds = 20;
console.log(averageSpeed(distance, time)); // 5
console.log(averageSpeed(time, distance)); // 0.2, compilesBoth calls return a number, so nothing looks broken. A second example involves money:
type Cents = number;
type Dollars = number;
function chargeCard(amount: Cents): void {
console.log(`charging ${amount} cents`);
}
const price: Dollars = 19.99;
chargeCard(price); // compiles: charges 19.99 cents instead of 1999The customer is undercharged by a factor of 100. A famous real-world class of failures, such as spacecraft losing contact over unit mismatches, follows this same pattern.
Why the usual defenses fall short
Teams often try to reduce these errors without changing the types. Each approach helps a little and leaves the core gap open.
| Defense | What it does | Why it is not enough |
|---|---|---|
| Aliases such as `type UserId = string` | Documents intent in signatures | Not checked by the compiler |
| Descriptive parameter names | Helps readers at the call site | The compiler ignores names when checking calls |
| Comments and naming conventions | Explains intent | Not checked, and they drift out of date |
| Unit tests | Catch known cases | Cover only the paths someone thought to test |
| Code review | Catches some mistakes | Does not scale, and people miss swapped arguments |
| Lint rules on variable names | Flags suspicious names | Heuristic, with many false positives and false negatives |
The aliases are the most tempting option because they look like type safety. They produce the feeling of a checked contract without the check. That is arguably worse than having no alias at all. A reader who sees OrderId in a signature trusts that the value is an order ID, and the compiler does not back that up.
A partial fix: template literal types
If your IDs follow a fixed prefix convention, template literal types can tell them apart:
type UserId = `u_${string}`;
type OrderId = `o_${string}`;
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId: UserId = "u_123";
loadOrder("o_456"); // OK
loadOrder(userId); // Error: `u_${string}` is not assignable to `o_${string}`This works, and you should use it when your data genuinely has that shape. It has limits:
- It needs distinct, reliable prefixes. Database-generated IDs such as UUIDs or integers have none.
- It does not apply to numbers.
MetersandSecondshave no prefix to inspect. - It checks format, not validity. Any string starting with
o_passes, whether or not it names a real order. - A plain
stringread from a request or a file is not assignable to these types. You must narrow or cast it, and this chapter does not cover how to do that safely.
The template literal approach distinguishes types by their shape. What the rest of this tutorial needs is a way to distinguish types that have exactly the same shape.
What we actually want
The examples above point to a set of requirements for a better approach:
UserIdandOrderIdmust be different types, so passing one where the other is expected is a compile error.- Each should still be usable as a
stringwhere a string is needed, for example when logging, concatenating, or calling.startsWith(). - The distinction should cost nothing at runtime. IDs should stay ordinary strings in memory and on the wire.
- There should be a controlled place where a raw
stringbecomes aUserId, so validation can happen once. - The same technique should work for numbers, so
MetersandSecondscannot be confused.
TypeScript has no built-in feature for this, such as a newtype keyword. Requirement 3 rules out a wrapper object for every value. The next chapter builds a technique that meets these requirements with an ordinary intersection type and a compile-time-only tag.
Common mistakes when diagnosing the problem
- Assuming the alias name is enforced. Hovering over a parameter shows
OrderId, and people infer that only order IDs are accepted. Only the underlying type is checked. - Expecting object shapes to behave the same way. Two object types with different property names are distinguished. Two with the same properties are not. Primitives have no properties to compare, so they are always identical to each other.
- Blaming the call site. The bug is rarely in the line that makes the call. The function signature is too permissive, and fixing it at the type level protects every caller at once.
Exercise
Given type Celsius = number; and type Fahrenheit = number;, the function function setThermostat(target: Celsius): void is called with const t: Fahrenheit = 72; setThermostat(t);. Does this compile, and why?
Show answer
It compiles. Celsius and Fahrenheit are aliases of number, so both resolve to the same type. The compiler compares only the underlying type, so a Fahrenheit value is accepted where a Celsius is expected. The thermostat would be set to 72 degrees Celsius.
Exercise
A teammate says: "We use type UserId = string and type OrderId = string, so the compiler already stops us from passing a user ID to loadOrder(id: OrderId)." What would you reply, and what would you check to prove it?
Show answer
The claim is wrong, because aliases do not create new types. To prove it, write const u: UserId = "u_1"; loadOrder(u); and compile it. It compiles without error. The aliases document intent for humans, but the compiler sees string in both places.
Exercise
List two situations where the template literal fix (type OrderId = o_${string}``) does not work.
Show answer
Any two of the following. IDs without a distinguishing prefix, such as UUIDs or auto-increment integers. Numeric values such as Meters and Seconds. Cases that need real validation, since any string with the right prefix passes. Values arriving as plain string, which are not assignable without a cast or narrowing.