Recall & Review
beginner
What is a phantom type in TypeScript?
A phantom type is a type parameter used only at compile time to add extra type safety without affecting the runtime code. It helps catch errors early by distinguishing types that are otherwise similar.
Click to reveal answer
beginner
Why use phantom types instead of regular types?
Phantom types let you add extra compile-time checks without adding runtime overhead. They help prevent mixing incompatible types that look similar but represent different concepts.Click to reveal answer
intermediate
How do phantom types affect the generated JavaScript code?
Phantom types do not appear in the generated JavaScript code because they are only used by the TypeScript compiler for type checking. They have zero runtime cost.
Click to reveal answer
intermediate
Example: What does this TypeScript code do?
<pre>type Meter = { value: number; _unit: 'meter' };
type Second = { value: number; _unit: 'second' };
function addMeters(a: Meter, b: Meter): Meter {
return { value: a.value + b.value, _unit: 'meter' };
}</pre>This code uses phantom types (_unit) to distinguish Meter and Second types. The addMeters function only accepts Meter types, preventing accidental mixing with Second types at compile time.
Click to reveal answer
intermediate
Can phantom types be used with generics in TypeScript?
Yes, phantom types are often used as generic type parameters that do not appear in runtime values but help enforce constraints and improve type safety during compilation.
Click to reveal answer
What is the main purpose of phantom types in TypeScript?
✗ Incorrect
Phantom types add compile-time safety but do not affect runtime code.
Which of these is true about phantom types?
✗ Incorrect
Phantom types are erased during compilation and do not exist at runtime.
How can phantom types help prevent bugs?
✗ Incorrect
Phantom types distinguish similar data types to avoid mixing them accidentally.
In this code snippet, what is '_unit' used for?
type Meter = { value: number; _unit: 'meter' };✗ Incorrect
The '_unit' property is a phantom type marker used only for compile-time checks.
Can phantom types be used with generic functions?
✗ Incorrect
Phantom types are often used as generic parameters to enforce constraints at compile time.
Explain what phantom types are and why they are useful in TypeScript.
Think about types that exist only during checking, not when the program runs.
You got /4 concepts.
Describe a simple example where phantom types prevent mixing incompatible units like meters and seconds.
Use a property that marks the unit but is not used at runtime.
You got /3 concepts.