打字稿:type' Promise< void>'不能分配给类型' void |破坏者'
编辑正在显示
类型'Promise'不能分配给类型'void | destructor'。
对于CheckUserLoggedIn(),请在使用效果中调用。
我可以通过执行const checkuserloggedin来摆脱它:但是
,这也许不是最理想的解决方法...
如果我做const checkuserloggedin:Promise:Promise 然后,我得到不同的错误:
此表达不可呼应。输入“承诺”没有电话 签名。
这不是我想要的...我希望它可以呼叫...我正在翻译/转换我的JavaScript文件为Typescript .....
useEffect(() => checkUserLoggedIn(), [])
// Check if user is logged in
const checkUserLoggedIn = async () => {
console.log('checkUserLoggedIn')
const res = await fetch(`${NEXT_URL}/api/user`)
const data = await res.json()
if (res.ok) {
setUser(data.user)
console.log('data.user', data.user)
router.push('/account/dashboard')
} else {
setUser(null)
}
}
The editor is showing
Type 'Promise' is not assignable to type 'void | Destructor'.
for the checkUserLoggedIn() call in useEffect.
I can get rid of it by doing const checkUserLoggedIn:any
However maybe that's not the most ideal way of solving this...
If I do const checkUserLoggedIn:Promise
I then get a different error:
This expression is not callable. Type 'Promise' has no call
signatures.
which is not what I want...I want it to be callable...I'm translating/converting my javascript file to typescript.....
useEffect(() => checkUserLoggedIn(), [])
// Check if user is logged in
const checkUserLoggedIn = async () => {
console.log('checkUserLoggedIn')
const res = await fetch(`${NEXT_URL}/api/user`)
const data = await res.json()
if (res.ok) {
setUser(data.user)
console.log('data.user', data.user)
router.push('/account/dashboard')
} else {
setUser(null)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
箭头功能以您描述的方式写入的方式,隐式从函数返回值。例如,此功能
()=> 4
返回值4
。相反,当您将其包裹在块中时,必须明确定义返回值:()=> {4; }
此功能不会返回任何内容。在您的情况下,您正在传递一个匿名箭头功能,该功能隐含地返回异步函数的结果,这是一个承诺。
要解决此问题,请将您传递给
usefect
的函数的内容包装在一个块中:Arrow functions written in the way you've described implicitly return the value from the function. For example, this function
() => 4
returns the value4
. Conversely, when you wrap this in a block, you must explicitly define the return value:() => { 4; }
this function does not return anything.In your case, you are passing an anonymous arrow function that implicitly returns the result of an asynchronous function, which is a promise.
To fix this, wrap the content of the function you pass to
useEffect
in a block: