user4383363
user4383363

Reputation:

Argument of type 'never[]' is not assignable to parameter of type 'never' when declaring a type in Typescript

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

Answers (1)

r3dst0rm
r3dst0rm

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

Related Questions