0
0
Typescriptprogramming~20 mins

Discriminated union state machines 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 state machine
What is the output of this TypeScript code that uses a discriminated union to represent states?
Typescript
type State =
  | { type: "loading" }
  | { type: "success"; data: string }
  | { type: "error"; message: string };

function getMessage(state: State): string {
  switch (state.type) {
    case "loading":
      return "Loading...";
    case "success":
      return `Data: ${state.data}`;
    case "error":
      return `Error: ${state.message}`;
  }
}

const currentState: State = { type: "success", data: "Hello" };
console.log(getMessage(currentState));
ALoading...
BError: Hello
CData: Hello
Dundefined
Attempts:
2 left
💡 Hint
Look at the type property of the currentState object and how the switch statement handles it.
Predict Output
intermediate
2:00remaining
Result of state transition function
Given this state machine transition function, what is the value of nextState after calling transition(currentState, "fail")?
Typescript
type State =
  | { type: "idle" }
  | { type: "loading" }
  | { type: "success"; data: number }
  | { type: "error"; message: string };

function transition(state: State, event: "start" | "succeed" | "fail"): State {
  switch (state.type) {
    case "idle":
      if (event === "start") return { type: "loading" };
      break;
    case "loading":
      if (event === "succeed") return { type: "success", data: 42 };
      if (event === "fail") return { type: "error", message: "Failed to load" };
      break;
    case "success":
    case "error":
      if (event === "start") return { type: "loading" };
      break;
  }
  return state;
}

const currentState: State = { type: "loading" };
const nextState = transition(currentState, "fail");
A{"type":"error","message":"Failed to load"}
B{"type":"success","data":42}
C{"type":"loading"}
D{"type":"idle"}
Attempts:
2 left
💡 Hint
Check the transition function's case for "loading" state and "fail" event.
🔧 Debug
advanced
2:00remaining
Identify the error in this discriminated union state machine code
This TypeScript code tries to handle states with a discriminated union, but it causes a compile-time error. What is the error?
Typescript
type State =
  | { status: "open" }
  | { status: "closed"; reason: string };

function handleState(state: State) {
  if (state.status === "open") {
    console.log("Open state");
  } else {
    console.log(state.reason);
  }
}

const s: State = { status: "open" };
handleState(s);
ACannot compare 'state.status' with string literal.
BType 'State' is not assignable to parameter of type 'string'.
CMissing return statement in function 'handleState'.
DProperty 'reason' does not exist on type '{ status: "open" }'.
Attempts:
2 left
💡 Hint
Check the else branch and what properties are accessed on the state object.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a discriminated union for a state machine?
Choose the correct TypeScript code snippet that defines a discriminated union type for a state machine with states: 'start', 'processing' with a progress number, and 'done' with a result string.
Atype State = { type: "start" } & { type: "processing", progress: number } & { type: "done", result: string };
Btype State = { type: "start" } | { type: "processing", progress: number } | { type: "done", result: string };
Ctype State = { type: "start" | "processing" | "done"; progress?: number; result?: string };
Dtype State = { type: string; progress: number; result: string };
Attempts:
2 left
💡 Hint
Discriminated unions use the '|' operator to combine distinct object types with a common discriminant property.
🚀 Application
expert
2:00remaining
Determine the number of possible states in this discriminated union state machine
Consider this TypeScript discriminated union representing a state machine. How many distinct states does it represent?
Typescript
type State =
  | { phase: "init" }
  | { phase: "running"; step: 1 | 2 | 3 }
  | { phase: "finished"; success: boolean };

// Count all possible distinct states represented by this type.
A6
B5
C7
D8
Attempts:
2 left
💡 Hint
Count each variant and multiply by the number of possible values for properties with unions.