Typescript is giving me an error: Expected 0 arguments, but got 1

bradrar picture bradrar · Jun 2, 2020 · Viewed 20.4k times · Source

I want to define the interface the proper way but I am having trouble because it is expecting an argument even though the argument is empty.

I am using useContext and I defined the interface like this:

    //react-auth0-spa.tsx
    interface Auth0Context {
        ......
        loginWithRedirect:  () => void; //I know this is the problem but I don't know what to define.
        ......
     }

in the provider, the value is :

 //react-auth0-spa.tsx
 <Auth0Context.Provider
     value=({
  ....
  loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)
   ....
   })
>

now, I import the context to other the other file like so: const { isAuthenticated, loginWithRedirect, logout } = useAuth0()

and this is where the error occurs

///components/NavBar.tsx
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
<div>
      {!isAuthenticated && (
        <button onClick={() => loginWithRedirect({})}>Log in</button> //Expected 0 arguments, but got 1
      )}
</div>

so the problem is loginWithRedirect is expecting 1 argument, but () => loginWithRedirect({}) is an empty object. The problem can be solved by using any inside the interface but what should I put if I want to define it explicitly?

I tried loginWithRedirect: ({}) => void but now loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p) is giving me error like this Type '{}' is not assignable to type 'string'.ts(2322)

source code without typescript is https://github.com/auth0-samples/auth0-react-samples/tree/master/01-Login/src

Please help.

Answer

Zain Ul Abideen picture Zain Ul Abideen · Jun 2, 2020

Problem in the first place is:

You provided signature of a function like this in the interface:

loginWithRedirect: () => void;

which means no argument and whenever you'll define that function you will obey this signature but in contrary you are passing argument to the function while giving it's definition.

Solution

Why not doing like this?

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