0
0
Typescriptprogramming~30 mins

Phantom types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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 Foot
Create variables with these phantom types
Write a function addLengths that accepts two lengths of the same phantom type and returns their sum
Try 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
1
Create phantom types for Meter and Foot
Create two empty interfaces called Meter and Foot to represent phantom types for units.
Typescript
Need a hint?

Phantom types are empty interfaces used only for type checking.

2
Create length variables with phantom types
Create two variables: lengthInMeters of type number & Meter with value 5, and lengthInFeet of type number & Foot with value 10.
Typescript
Need a hint?

Use as number & Meter to assign the phantom type to the number value.

3
Write addLengths function for same phantom types
Write a function called addLengths that takes two parameters a and b of the same generic phantom type T (which extends Meter or Foot) and returns their sum as number & T. Use a generic type parameter T to enforce the same phantom type.
Typescript
Need a hint?

Use a generic type T to ensure both parameters have the same phantom type.

4
Add lengths and print the result
Use the addLengths function to add lengthInMeters to itself and print the result using console.log. The output should be 10.
Typescript
Need a hint?

Call addLengths(lengthInMeters, lengthInMeters) and print the result.