Reputation:
I am learning Typescript and following a tutorial, I wrote this code:
interface Todo {
text: string;
completed: boolean;
}
type State = Array<Todo>;
const TodoReducer = (state: State, action: Actions) => {
switch (action.type) {
case "add":
return console.log("add");
case "remove":
return console.log("remove");
default:
}
};
const Input: React.FC<Props> = ({ name, onChange }) => {
...
const [todos, dispatch] = React.useReducer(TodoReducer, []);
...
};
But unlike the tutorial, in my case, I am seeing the error
Argument of type 'never[]' is not assignable to parameter of type 'never'
Pointing to
29 | const [todos, dispatch] = React.useReducer(TodoReducer, []);
Upvotes: 2
Views: 5504
Reputation: 1926
The TodoReducer must return a valid state for each case - event the default.
So something along the lines would work for your example to be valid. I did introduce a default state of an empty array []
and returned state
for each action type. This you would have to adjust to your needs.
interface Todo {
text: string;
completed: boolean;
}
type State = Array<Todo>;
const TodoReducer = (state: State = [], action: Actions) => { // added a default state
switch (action.type) {
case "add":
console.log("add");
return state; // return your desired state
case "remove":
console.log("remove");
return state; // return your desired state
default:
return state; // you did miss return state or similar here in your example
}
};
const Input: React.FC<Props> = ({ name, onChange }) => {
...
const [todos, dispatch] = React.useReducer(TodoReducer, []);
...
};
Upvotes: 1