首页 > 解决方案 > 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

请帮忙。

标签: reactjstypescriptuse-context

解决方案


首先的问题是:

您在界面中提供了这样的函数签名:

loginWithRedirect: () => void;

这意味着没有参数,无论何时定义该函数,您都将遵守此签名,但相反,您在给出定义时将参数传递给函数。

解决方案

为什么不这样做呢?

//react-auth0-spa.tsx
    interface Auth0Context {
        ......
        loginWithRedirect:  (p: object) => void;
        ......
     }

推荐阅读