在Typescript中声明类型时,类型'never []'的参数不能分配给类型'never'的参数

时间:2019-12-09 12:48:50

标签: javascript reactjs typescript

我正在学习Typescript,并按照一个教程编写了以下代码:

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, []);
  ...
};

但是与本教程不同,我遇到的错误是

  

'never []'类型的参数不能分配给'never'类型的参数

指向

  

29 | const [todos,dispatch] = React.useReducer(TodoReducer,[]);

1 个答案:

答案 0 :(得分:0)

对于每种情况,TodoReducer必须返回有效状态-如果是默认情况,则为

因此,对于您的示例来说,可以采用一些类似的方法。我确实引入了空数组[]的默认状态,并为每种操作类型返回了state。您必须根据需要进行调整。

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, []);
  ...
};