Bird
Raised Fist0
Typescriptprogramming~20 mins

Discriminated unions in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Discriminated Union Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple discriminated union function
What is the output of the following TypeScript code?
Typescript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size ** 2;
  }
}

console.log(area({ kind: "circle", radius: 3 }));
ATypeError at runtime
B9
C28.274333882308138
Dundefined
Attempts:
2 left
πŸ’‘ Hint
Recall the formula for the area of a circle is Ο€ Γ— radiusΒ².
🧠 Conceptual
intermediate
2:00remaining
Discriminated union type narrowing
Given the discriminated union below, which statement correctly narrows the type inside the if block?
Typescript
type Pet =
  | { type: "dog"; barkVolume: number }
  | { type: "cat"; livesLeft: number };

function speak(pet: Pet) {
  if (/* which condition? */) {
    console.log(pet.barkVolume);
  }
}
Apet.type === "dog"
Bpet.livesLeft > 0
Cpet.type === "cat"
Dpet.barkVolume !== undefined
Attempts:
2 left
πŸ’‘ Hint
Discriminated unions use a common literal property to narrow types.
πŸ”§ Debug
advanced
2:00remaining
Identify the error in discriminated union switch
What error will this TypeScript code produce?
Typescript
type Vehicle =
  | { kind: "car"; wheels: 4 }
  | { kind: "bike"; wheels: 2 };

function describe(vehicle: Vehicle) {
  switch (vehicle.kind) {
    case "car":
      return `Car with ${vehicle.wheels} wheels`;
    case "bike":
      return `Bike with ${vehicle.wheels} wheels`;
    case "truck":
      return "Truck";
  }
}
AError: Object is possibly 'undefined' in switch default
BError: Missing return statement in function
CNo error, code compiles fine
DError: Type '"truck"' is not assignable to type '"car" | "bike"'
Attempts:
2 left
πŸ’‘ Hint
Check the switch cases against the union type's possible 'kind' values.
πŸ“ Syntax
advanced
2:00remaining
Correct syntax for discriminated union with literal types
Which option correctly defines a discriminated union type for a shape with 'kind' as the discriminator?
Atype Shape = { kind: string, radius: number } | { kind: string, size: number };
Btype Shape = { kind: "circle", radius: number } | { kind: "square", size: number };
Ctype Shape = { kind: "circle" | "square", radius?: number, size?: number };
Dtype Shape = { kind: "circle" & "square", radius: number, size: number };
Attempts:
2 left
πŸ’‘ Hint
Discriminated unions require a common property with distinct literal values.
πŸš€ Application
expert
3:00remaining
Determine the output of a complex discriminated union function
What is the output of this TypeScript code?
Typescript
type Event =
  | { type: "click"; x: number; y: number }
  | { type: "keypress"; key: string };

function handleEvent(e: Event): string {
  switch (e.type) {
    case "click":
      return `Clicked at (${e.x},${e.y})`;
    case "keypress":
      return `Key pressed: ${e.key}`;
  }
}

console.log(handleEvent({ type: "keypress", key: "Enter" }));
AKey pressed: Enter
BClicked at (undefined,undefined)
CTypeError at runtime
Dundefined
Attempts:
2 left
πŸ’‘ Hint
Check which case matches the event type and what properties are accessed.

Practice

(1/5)
1.

What is the main purpose of a discriminated union in TypeScript?

easy
A. To automatically convert types at runtime
B. To create a union of unrelated primitive types
C. To enforce a single type for all variables
D. To distinguish between different object types using a common property

Solution

  1. Step 1: Understand discriminated unions

    Discriminated unions use a shared property (called the discriminant) to identify which type an object belongs to.
  2. Step 2: Purpose of discriminated unions

    This helps TypeScript safely narrow types in code by checking that property.
  3. Final Answer:

    To distinguish between different object types using a common property -> Option D
  4. Quick Check:

    Discriminated union = common property to tell types apart [OK]
Hint: Look for a shared property that identifies each type [OK]
Common Mistakes:
  • Thinking discriminated unions convert types automatically
  • Confusing with simple unions of primitives
  • Believing they enforce one single type only
2.

Which of the following is the correct syntax to define a discriminated union type in TypeScript?

type Shape = ?
easy
A. type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; side: number }
B. type Shape = { radius: number } & { side: number }
C. type Shape = { kind: string; radius?: number; side?: number }
D. type Shape = { circle: number } | { square: number }

Solution

  1. Step 1: Identify discriminant property

    type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; side: number } uses a common property kind with literal types ('circle' or 'square') to discriminate.
  2. Step 2: Check union structure

    type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; side: number } correctly uses a union of two object types distinguished by kind.
  3. Final Answer:

    type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; side: number } -> Option A
  4. Quick Check:

    Discriminated union = union with common literal property [OK]
Hint: Look for union with a shared literal property for discrimination [OK]
Common Mistakes:
  • Using intersection (&) instead of union (|)
  • Missing literal type for discriminant property
  • Using optional properties without discriminant
3.

What will be the output of the following TypeScript code?

type Animal =
  | { type: 'dog'; barkVolume: number }
  | { type: 'cat'; livesLeft: number };

function describe(animal: Animal) {
  switch (animal.type) {
    case 'dog':
      return `Dog barks at volume ${animal.barkVolume}`;
    case 'cat':
      return `Cat has ${animal.livesLeft} lives left`;
  }
}

console.log(describe({ type: 'cat', livesLeft: 7 }));
medium
A. Cat has 7 lives left
B. Dog barks at volume undefined
C. TypeError at runtime
D. Cat has undefined lives left

Solution

  1. Step 1: Analyze the input object

    The input is { type: 'cat', livesLeft: 7 }, so the type is 'cat'.
  2. Step 2: Follow the switch case

    The switch matches 'cat' case and returns `Cat has ${animal.livesLeft} lives left`, which becomes 'Cat has 7 lives left'.
  3. Final Answer:

    Cat has 7 lives left -> Option A
  4. Quick Check:

    Switch on discriminant returns correct string [OK]
Hint: Match the discriminant property in switch to get output [OK]
Common Mistakes:
  • Confusing 'dog' and 'cat' cases
  • Expecting runtime error due to union
  • Ignoring the discriminant property
4.

Identify the error in this TypeScript code using discriminated unions:

type Vehicle =
  | { kind: 'car'; wheels: number }
  | { kind: 'bike'; pedals: number };

function getWheels(vehicle: Vehicle) {
  if (vehicle.kind === 'car') {
    return vehicle.wheels;
  } else {
    return vehicle.wheels;
  }
}
medium
A. Function should use switch instead of if
B. Property 'wheels' does not exist on type 'bike' object
C. Incorrect discriminant property name
D. Missing return type annotation on function

Solution

  1. Step 1: Check property access in else branch

    In the else branch, the code accesses vehicle.wheels, but bike type has no wheels property.
  2. Step 2: Understand TypeScript error

    This causes a type error because wheels is not defined for { kind: 'bike'; pedals: number }.
  3. Final Answer:

    Property 'wheels' does not exist on type 'bike' object -> Option B
  4. Quick Check:

    Accessing wrong property on union member causes error [OK]
Hint: Check property exists on all union members before access [OK]
Common Mistakes:
  • Assuming all union members share same properties
  • Ignoring TypeScript error messages
  • Thinking switch is mandatory over if
5.

Given the following discriminated union, how can you safely add a new shape type rectangle with width and height properties and update the area function accordingly?

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'square':
      return shape.side ** 2;
  }
}
hard
A. Add { kind: 'rectangle'; width: number; height: number } to Shape union and replace switch with if-else
B. Add { kind: 'rectangle'; width: number; height: number } to Shape union but no change needed in area function
C. Add { kind: 'rectangle'; width: number; height: number } to Shape union and add case 'rectangle' in switch returning width * height
D. Add { kind: 'rectangle'; width: number; height: number } to Shape union and remove existing cases

Solution

  1. Step 1: Extend the union type

    Add the new shape type with discriminant kind: 'rectangle' and properties width and height to the Shape union.
  2. Step 2: Update the area function

    Add a new case in the switch for 'rectangle' that returns shape.width * shape.height to correctly calculate the area.
  3. Final Answer:

    Add { kind: 'rectangle'; width: number; height: number } to Shape union and add case 'rectangle' in switch returning width * height -> Option C
  4. Quick Check:

    Extend union and handle new case in switch [OK]
Hint: Add new type to union and handle it in switch [OK]
Common Mistakes:
  • Forgetting to update the function for new type
  • Removing existing cases accidentally
  • Not using discriminant property in new type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard