What if your code could catch sneaky mistakes that look right but cause big problems?
Why Phantom types in Typescript? - Purpose & Use Cases
Imagine you have different kinds of IDs in your program, like UserID and ProductID, both just numbers. You try to keep them separate by naming variables carefully, but nothing stops you from mixing them up by accident.
Manually tracking which number means what is slow and risky. You might pass a ProductID where a UserID is expected, causing bugs that are hard to find. The compiler can't help because both are just numbers.
Phantom types let you add invisible tags to your data types. These tags don't change the actual data but tell the compiler to treat them as different types. This way, you can't mix UserID and ProductID by mistake, and errors are caught early.
function getUserName(id: number) { /* ... */ }
function getProductName(id: number) { /* ... */ }
getUserName(productId); // No error, but wrong!type UserID = number & { readonly brand: unique symbol };
type ProductID = number & { readonly brand: unique symbol };
function getUserName(id: UserID) { /* ... */ }
function getProductName(id: ProductID) { /* ... */ }
const productId: ProductID = 123 as ProductID;
getUserName(productId); // Error: Type 'ProductID' is not assignable to type 'UserID'Phantom types enable safer code by letting the compiler catch mix-ups between similar data types before your program runs.
In a banking app, phantom types can keep AccountNumber and TransactionID separate, preventing costly mistakes like sending money to the wrong account.
Phantom types add invisible tags to data for extra safety.
They prevent mixing up similar types like IDs or units.
This leads to fewer bugs and more reliable programs.
Practice
phantom types in TypeScript?Solution
Step 1: Understand phantom types concept
Phantom types add extra type information that exists only at compile time and does not affect the actual data or runtime behavior.Step 2: Compare options with concept
Only To add extra type information without affecting runtime data correctly states that phantom types add extra type info without changing runtime data. Other options describe unrelated concepts.Final Answer:
To add extra type information without affecting runtime data -> Option CQuick Check:
Phantom types = extra compile-time info [OK]
- Thinking phantom types create new objects
- Confusing phantom types with runtime data changes
- Believing phantom types improve runtime performance
Solution
Step 1: Identify phantom type syntax
Phantom types use intersection with a unique symbol or branded property to add phantom info without changing the base type.Step 2: Check each option
type UserId = string & { readonly __brand: unique symbol } uses intersection with a unique symbol brand, which is the correct phantom type pattern. Others are normal types or unions.Final Answer:
type UserId = string & { readonly __brand: unique symbol } -> Option AQuick Check:
Phantom type = base type & unique brand [OK]
- Using union types instead of intersection for phantom types
- Declaring phantom types as arrays or simple types
- Missing the unique symbol branding
type Meter = number & { readonly __unit: 'meter' };
function addDistance(a: Meter, b: Meter): Meter {
return (a + b) as Meter;
}
const dist1 = 5 as Meter;
const dist2 = 10 as Meter;
const total = addDistance(dist1, dist2);
console.log(total);Solution
Step 1: Understand phantom type behavior at runtime
Phantom types exist only at compile time. At runtime, they are just numbers. So adding two numbers works normally.Step 2: Analyze code output
dist1 and dist2 are numbers with phantom type. Adding them returns 15, which is logged.Final Answer:
15 -> Option BQuick Check:
Phantom types don't affect runtime value [OK]
- Expecting type errors at runtime
- Thinking phantom types change runtime values
- Confusing phantom types with runtime wrappers
type UserId = string & { readonly __brand: unique symbol };
function getUser(id: UserId) {
return `User: ${id}`;
}
const id = 'abc123';
getUser(id);Solution
Step 1: Check argument type for getUser
getUser expects a UserId (string with phantom brand). Passing plain string 'abc123' lacks the brand, causing a type error.Step 2: Validate other options
Return type is correct, unique symbol usage is valid, and code does not run fine due to type mismatch.Final Answer:
Passing a plain string instead of branded UserId causes a type error -> Option DQuick Check:
Phantom type mismatch = type error [OK]
- Ignoring phantom brand when passing values
- Thinking unique symbol is invalid in types
- Assuming no error when types differ
Consider these types:
type UserId = string & { readonly __brand: 'UserId' };
type ProductId = string & { readonly __brand: 'ProductId' };What is the main benefit of this approach?
Solution
Step 1: Understand phantom branding for IDs
Phantom types add unique brands to similar base types (string) to distinguish them at compile time.Step 2: Identify benefit in type safety
This branding prevents passing a ProductId where a UserId is expected, catching errors before running code.Final Answer:
It prevents accidentally using a ProductId where a UserId is expected at compile time -> Option AQuick Check:
Phantom types enforce distinct types safely [OK]
- Thinking phantom types affect runtime performance
- Assuming automatic conversion between branded types
- Believing phantom types allow mixing without errors
Ready to prove it?
Pass the test and this pattern moves unknown
