我想以正确的方式定义接口(interface),但我遇到了麻烦,因为即使参数为空,它也需要一个参数。
我正在使用 useContext
我定义了这样的接口(interface):
//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)
没有 typescript 的源代码是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;
......
}
关于reactjs - typescript 给我一个错误 : Expected 0 arguments, 但得到 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62146182/