gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:19:59 25 4
gpt4 key购买 nike

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

但与教程不同的是,就我而言,我看到了错误

Argument of type 'never[]' is not assignable to parameter of type 'never'

指向

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

最佳答案

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

关于javascript - 在 Typescript 中声明类型时,类型 'never[]' 的参数不可分配给类型 'never' 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59249256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com