0
0
Typescriptprogramming~20 mins

Discriminated unions in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 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.