0
0
Typescriptprogramming~10 mins

Discriminated union state machines in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a discriminated union type for a state machine with states 'idle' and 'loading'.

Typescript
type State = { status: 'idle' } | { status: [1] };
Drag options to blanks, or click blank then click option'
A'done'
B'loading'
C'error'
D'start'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a state name not defined in the union, like 'done' or 'error'.
2fill in blank
medium

Complete the code to create a function that returns true if the state is 'loading'.

Typescript
function isLoading(state: State): boolean {
  return state.status === [1];
}
Drag options to blanks, or click blank then click option'
A'loading'
B'idle'
C'done'
D'error'
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing to 'idle' or other incorrect states.
3fill in blank
hard

Fix the error in the switch statement to handle all states correctly.

Typescript
function handleState(state: State) {
  switch (state.status) {
    case 'idle':
      return 'Waiting';
    case [1]:
      return 'Loading data';
    default:
      return 'Unknown';
  }
}
Drag options to blanks, or click blank then click option'
A'done'
B'error'
C'loading'
D'start'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a case label that doesn't match any state, causing the default case to run.
4fill in blank
hard

Fill both blanks to define a state machine with 'success' and 'failure' states using discriminated unions.

Typescript
type ResultState = { status: [1]; data: string } | { status: [2]; error: string };
Drag options to blanks, or click blank then click option'
A'success'
B'loading'
C'failure'
D'idle'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing unrelated states like 'loading' or 'idle' here.
5fill in blank
hard

Fill all three blanks to create a function that returns a message based on the ResultState.

Typescript
function getMessage(state: ResultState): string {
  switch (state.status) {
    case [1]:
      return `Data: ${state.[2]`;
    case [3]:
      return `Error: ${state.error}`;
  }
}
Drag options to blanks, or click blank then click option'
A'success'
Bdata
C'failure'
Dstatus
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong property names or case labels that don't match the union.