【问题标题】:Argument of type 'never[]' is not assignable to parameter of type 'never' when declaring a type in Typescript在 Typescript 中声明类型时,“never[]”类型的参数不能分配给“never”类型的参数
【发布时间】:2019-12-09 12:48:50
【问题描述】:

我正在学习 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, []);

【问题讨论】:

  • 尝试为状态const TodoReducer = (state: State = [], action: Actions): State =&gt; { 分配一个默认值,同时添加一个默认情况:default: return []。目前你的减速器没有返回任何东西,为addremove 的情况分配一些回报
  • 好吧,看来已经解决了。我想知道这是否是由于最近的更新,因为我正在关注的教程只有 3 个月大。问题是添加: State =&gt;
  • 显然useReducer 期望减速器返回一些东西:)

标签: javascript reactjs typescript


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 2021-06-09
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2020-05-30
    • 2021-07-02
    相关资源
    最近更新 更多