类型 '(res: bookContent) => void' 的参数不可分配



我是TS的新手,在调用我的数据库的useEffect()中获得此类型错误。我不确定我做错了什么。我读到,这是因为我没有返回任何东西,但这个函数不需要返回任何东西…但我也可能错了。

Argument of type '(res: bookContent) => void' is not assignable to parameter of type '(value: bookContent | undefined) => void | PromiseLike<void>'.
Types of parameters 'res' and 'value' are incompatible.
Type 'bookContent | undefined' is not assignable to type 'bookContent'.
Type 'undefined' is not assignable to type 'bookContent'

代码如下:

useEffect(() => {
services.bookData
.getBookInfo(bookID)
.then((res: bookContent) => {
if (res) {
setContent({
id: res.id,
name: res.name,
info: res.info,
type: res.type,
});
dispatch(bookContentThunk(content));
}
})
.catch((err: any) => {
throw new Error(`Error in retrieving book details. ${err}`);
});
}, [user.status]);

getBookInfo可以返回bookContent | undefined(也建议在bookContent类型中添加大写,以避免混淆)。

指定一个函数,将其参数描述为(res: bookContent)。Typescript抱怨res也可以是undefined,因此Types of parameters 'res' and 'value' are incompatible.

要解决这个问题,您应该将res设置为bookContent | undefined:

useEffect(() => {
services.bookData
.getBookInfo(bookID)
.then((res: bookContent | undefined) => {
if (res) {
setContent({
id: res.id,
name: res.name,
info: res.info,
type: res.type,
});
dispatch(bookContentThunk(content));
}
})
.catch((err: any) => {
throw new Error(`Error in retrieving book details. ${err}`);
});
}, [user.status]);

相关内容

最新更新