TypeScript · Senior · Question 48 of 75
How do you type a reducer so that payload depends on the action's type?
- ✓Correct answer: Describe the actions as a union discriminated by the
typefield - 2Make
payload: anyand check it in everycase - 3Create one
Actioninterface with all fields optional
Explanation
type Action = { type: 'add'; payload: Todo } | { type: 'remove'; payload: { id: string } } - in case 'add' TS knows payload is a Todo. With never in default you get an exhaustiveness check. Redux Toolkit generates such types automatically from createSlice.