Complete the code to define a discriminated union type for a state machine with states 'idle' and 'loading'.
type State = { status: 'idle' } | { status: [1] };The discriminated union uses the 'status' property to distinguish states. Here, 'loading' is the correct second state.
Complete the code to create a function that returns true if the state is 'loading'.
function isLoading(state: State): boolean {
return state.status === [1];
}The function checks if the state's status is 'loading' to return true.
Fix the error in the switch statement to handle all states correctly.
function handleState(state: State) {
switch (state.status) {
case 'idle':
return 'Waiting';
case [1]:
return 'Loading data';
default:
return 'Unknown';
}
}The switch must handle the 'loading' state to return the correct message.
Fill both blanks to define a state machine with 'success' and 'failure' states using discriminated unions.
type ResultState = { status: [1]; data: string } | { status: [2]; error: string };The discriminated union defines 'success' with data and 'failure' with error.
Fill all three blanks to create a function that returns a message based on the ResultState.
function getMessage(state: ResultState): string {
switch (state.status) {
case [1]:
return `Data: ${state.[2]`;
case [3]:
return `Error: ${state.error}`;
}
}The function checks if the state is 'success' or 'failure' and returns the appropriate message using the correct property.