Using Phantom Types in TypeScript
📖 Scenario: You are building a simple system to handle different units of measurement safely. You want to avoid mixing units like meters and feet by mistake in your calculations.
🎯 Goal: Create phantom types in TypeScript to represent Meter and Foot units. Then write a function that adds two lengths only if they have the same unit type, preventing accidental mixing.
📋 What You'll Learn
Create phantom types for
Meter and FootCreate variables with these phantom types
Write a function
addLengths that accepts two lengths of the same phantom type and returns their sumTry to add lengths of different phantom types and observe the TypeScript error
Print the result of adding two lengths of the same phantom type
💡 Why This Matters
🌍 Real World
Phantom types help prevent bugs in programs that deal with different units, currencies, or states by making sure incompatible types are not mixed accidentally.
💼 Career
Understanding phantom types is useful for writing safer TypeScript code in finance, engineering, or any domain where data correctness is critical.
Progress0 / 4 steps