Challenge - 5 Problems
Discriminated Union Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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));Attempts:
2 left
💡 Hint
Look at the type property of the currentState object and how the switch statement handles it.
✗ Incorrect
The currentState has type "success" with data "Hello". The switch case for "success" returns `Data: ${state.data}`, so the output is "Data: Hello".
❓ Predict Output
intermediate2: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");Attempts:
2 left
💡 Hint
Check the transition function's case for "loading" state and "fail" event.
✗ Incorrect
When state is "loading" and event is "fail", the function returns { type: "error", message: "Failed to load" }.
🔧 Debug
advanced2: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);Attempts:
2 left
💡 Hint
Check the else branch and what properties are accessed on the state object.
✗ Incorrect
In the else branch, TypeScript cannot guarantee that 'state' has the 'reason' property because it could be the 'open' variant without 'reason'. This causes a compile-time error.
📝 Syntax
advanced2: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.
Attempts:
2 left
💡 Hint
Discriminated unions use the '|' operator to combine distinct object types with a common discriminant property.
✗ Incorrect
Option B correctly uses union types with distinct 'type' literals and appropriate properties. Option B uses intersection (&) which merges all properties and is incorrect here. Option B uses a single type with optional properties, losing type safety. Option B uses general string and all properties, losing discrimination.
🚀 Application
expert2: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.Attempts:
2 left
💡 Hint
Count each variant and multiply by the number of possible values for properties with unions.
✗ Incorrect
The 'init' phase has 1 state. The 'running' phase has 3 states (step 1, 2, or 3). The 'finished' phase has 2 states (success true or false). Total states = 1 + 3 + 2 = 6.