What is a phantom type?
- TypeScript course
- Advanced
- Lesson 21/57
- 4 min
Learn safety with phantom type parameters.
What is a phantom type?
A phantom type is a generic type parameter that is declared but never used in the type's body. This parameter carries information only at the type level; it has no runtime representation. Its purpose is to mark values with the same structure as distinct types, catching misuse at compile time.
type Order<T> = { amount: number };
// T is not used in the body: phantom
type PendingOrder = Order<"pending">;
type PaidOrder = Order<"paid">;Nominal-like safety with phantoms
The phantom parameter replaces the marker field of branded types. Two values with the same structure but different phantom arguments become distinct types; this prevents mixing them at compile time. At runtime the values are identical.
type Order<T> = { amount: number };
const pending: Order<"pending"> = { amount: 10 };
const paid: Order<"paid"> = { amount: 10 };
const x: Order<"paid"> = pending; // error: types differPractice Separate two types with phantoms
Define a generic type Order<T> that doesn't use T in its body (body has amount: number). Create PendingOrder and PaidOrder types with phantom arguments. Create a value of each type and print both amount values via console.log.
Starter code
// Order<T> generic türünü tanımla (T gövdede kullanılmasın)
// PendingOrder ve PaidOrder türlerini phantom argümanlarla oluştur
// Her türden bir değer oluştur ve amount değerlerini yazdırSample solution
type Order<T> = { amount: number };
type PendingOrder = Order<"pending">;
type PaidOrder = Order<"paid">;
const pending: PendingOrder = { amount: 10 };
const paid: PaidOrder = { amount: 20 };
console.log(pending.amount);
console.log(paid.amount);Expected output
10 20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What property does a phantom type parameter have?
- It is ignored at compile time
- It is never used in the type's body Correct answer
- It carries a value at runtime
- It can only be used in classes
Explanation: A phantom parameter is declared as generic but never used in the type's body; therefore it works only as a type-level marker.
2 Phantom type body
type Order<T> = { ____ }; // T gövdede yok: phantom
type Order<T> = { amount: number }; // T gövdede yok: phantom
Explanation: The amount: number property does not use the T parameter; thus T remains phantom and different arguments create distinct types.
3 Phantom type parts
| Term | Meaning |
|---|---|
Generic parametre |
not used in type body |
Phantom type |
type-level marker only |
Farklı phantom argümanlar |
create distinct types |
Çalışma zamanı |
no phantom parameter at runtime |