reactjs - Typescript 给了我一个错误:Expected 0 arguments, but got 1
问题描述
我想以正确的方式定义接口,但我遇到了麻烦,因为即使参数为空,它也需要一个参数。
我正在使用useContext
并且我定义了这样的接口:
//react-auth0-spa.tsx
interface Auth0Context {
......
loginWithRedirect: () => void; //I know this is the problem but I don't know what to define.
......
}
在提供者中,value
是:
//react-auth0-spa.tsx
<Auth0Context.Provider
value=({
....
loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)
....
})
>
现在,我import
将上下文添加到其他文件,如下所示:
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
这就是发生错误的地方
///components/NavBar.tsx
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
<div>
{!isAuthenticated && (
<button onClick={() => loginWithRedirect({})}>Log in</button> //Expected 0 arguments, but got 1
)}
</div>
所以问题是loginWithRedirect
期待 1 个参数,但() => loginWithRedirect({})
它是一个空对象。这个问题可以通过any
在接口内部使用来解决,但是如果我想明确定义它应该放什么?
我试过loginWithRedirect: ({}) => void
但现在loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)
给我这样的错误Type '{}' is not assignable to type 'string'.ts(2322)
没有打字稿的源代码是https://github.com/auth0-samples/auth0-react-samples/tree/master/01-Login/src
请帮忙。
解决方案
首先的问题是:
您在界面中提供了这样的函数签名:
loginWithRedirect: () => void;
这意味着没有参数,无论何时定义该函数,您都将遵守此签名,但相反,您在给出定义时将参数传递给函数。
解决方案
为什么不这样做呢?
//react-auth0-spa.tsx
interface Auth0Context {
......
loginWithRedirect: (p: object) => void;
......
}
推荐阅读
- go - Goland 从按钮单击运行/重新运行命令
- swiftui - 如何在 LinearGradient 初始化程序中使用变量 - SwiftUI
- html - 为什么下面提到的代码无法区分
标题和普通文本? - python - Python:如何将包含额外分隔符的字符串拆分为值
- javascript - 在 CSS 3D 旋转画布上获取鼠标坐标
- android - 在转换为自定义对象之前检查 json
- javascript - Redux + TypeScript 和 mapDispatchToProps
- mysql - 根据错误 1364,id 值需要默认值吗?
- python - How to simplify/what to use these if statements?
- java - I have created custom jList renderer but i am not able to get the selected cell text