Phantom types in Typescript - Time & Space Complexity
We want to see how using phantom types affects the speed of our TypeScript code.
Specifically, does adding phantom types change how long the program takes as input grows?
Analyze the time complexity of the following TypeScript code using phantom types.
type Phantom<T> = { _phantom?: T };
function addLengths<T>(a: string & Phantom<T>, b: string & Phantom<T>): number {
return a.length + b.length;
}
const s1 = "hello" as string & Phantom<'A'>;
const s2 = "world" as string & Phantom<'A'>;
console.log(addLengths(s1, s2));
This code uses phantom types to tag strings without changing runtime behavior.
Look for loops or repeated steps that affect speed.
- Primary operation: Calculating string lengths with
a.lengthandb.length. - How many times: Each length is accessed once per function call.
As input strings get longer, the time to get their length grows very little because length is a stored property.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 length checks |
| 100 | 2 length checks |
| 1000 | 2 length checks |
Pattern observation: The number of operations stays the same no matter how long the strings are.
Time Complexity: O(1)
This means the function runs in constant time regardless of input size.
[X] Wrong: "Phantom types add extra work at runtime and slow down the program."
[OK] Correct: Phantom types exist only at compile time and do not affect runtime speed or operations.
Understanding phantom types helps you write safer code without slowing it down, a skill valued in real projects.
What if the function processed each character of the strings instead of just their lengths? How would the time complexity change?
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
