Web Development
TypeScript
Subjective
Oct 04, 2025
Explain the concept of phantom types in TypeScript.
Detailed Explanation
Phantom types use type parameters that exist only at compile time for type safety.
Basic phantom type:
type Phantom = T & { __phantom: P };
type Meters = Phantom;
type Feet = Phantom;
function createMeters(value: number): Meters {
return value as Meters;
}
function addMeters(a: Meters, b: Meters): Meters {
return (a + b) as Meters;
}
Usage example:
const m1 = createMeters(10);
const m2 = createMeters(20);
const result = addMeters(m1, m2); // OK
// addMeters(m1, createFeet(30)); // Error
Benefits: Compile-time safety, zero runtime cost, prevents value mixing.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts