[英]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:我正在学习 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, []);
...
};
But unlike the tutorial, in my case, I am seeing the error但与教程不同,就我而言,我看到了错误
Argument of type 'never[]' is not assignable to parameter of type 'never'
“never[]”类型的参数不可分配给“never”类型的参数
Pointing to指向
29 |
29 | const [todos, dispatch] = React.useReducer(TodoReducer, []);
const [todos, dispatch] = React.useReducer(TodoReducer, []);
The TodoReducer must return a valid state for each case - event the default. TodoReducer 必须为每种情况返回一个有效状态 - 事件默认。
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.我确实引入了一个空数组
[]
的默认状态,并为每个操作类型返回了state
。 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, []);
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.