TypeScript · Senior · Question 48 of 75

How do you type a reducer so that payload depends on the action's type?

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.

Further reading

Problem with a question

TypeScript · Senior · question 48

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz