Type-safety with UnknownAction in TypeScript
Show how to strongly type the UnknownAction in TypeScript to ensure reducers handle it correctly.
interface KnownAction {
type: 'ACTION_TYPE1' | 'ACTION_TYPE2';
// Other properties specific to known actions
}
interface UnknownAction {
type: 'UNKNOWN_ACTION';
}
type Action = KnownAction | UnknownAction;
function isKnownAction(action: Action): action is KnownAction {
return 'type' in action && action.type !== 'UNKNOWN_ACTION';
}
function reducer(state: any = {}, action: Action) {
if (isKnownAction(action)) {
switch (action.type) {
case 'ACTION_TYPE1':
// Handle ACTION_TYPE1
break;
case 'ACTION_TYPE2':
// Handle ACTION_TYPE2
break;
default:
// Ensure exhaustiveness of switch
const exhaustiveCheck: never = action;
break;
}
} else {
// Handle unknown action
}
return state;
}
Define TypeScript interfaces for known and unknown actions, then use a type guard function to determine if an action is known. In the reducer, handle known actions in a switch statement, ensuring type safety and exhaustiveness, while providing a default case for unknown actions.