【发布时间】:2020-09-20 13:52:16
【问题描述】:
我想以正确的方式定义接口,但我遇到了麻烦,因为即使参数为空,它也需要一个参数。
我正在使用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
请帮忙。
【问题讨论】:
-
你的问题标题和描述有点矛盾。标题说它期待 0 个参数意味着它根本不期待任何参数。描述说它需要 1 个参数。
-
loginWithRedirect可以调用的参数类型是什么? -
如果不清楚,抱歉。我需要更改接口
loginWithRedirect: () => void;以便我可以使用<button onClick={() => loginWithRedirect({})}>这意味着我需要在接口中提供一个我不知道该怎么做的参数 -
@Ali 我在界面中使用了
loginWithRedirect: any;,它正在工作。问题是,我需要明确定义它。我面临的问题是,如果接口为空,如何在接口中定义参数?<button onClick={() => loginWithRedirect({})}
标签: reactjs typescript use-context