Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property does not exist on type '{}' AND Expected 0 type arguments, but got 1

I’ve a hook useAuth() that handles the user in context.

import { useContext } from "react";
import AuthContext from "../context/AuthContext_Provider"

//AuthContext has been declared: const AuthContext = createContext({});
const useAuth = () => {
    return useContext(AuthContext) 
}

export default useAuth

Now, I’m wondering how the h to call this function?

Below yields the error Property ‘auth’ does not exist on type ‘{}’.ts(2339)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const { auth } = useAuth()

And if I try to add any kind of type any, object, {}, React.Context or even {auth:{username:string}} like below, i get another error saying: Expected 0 type arguments, but got 1.ts(2558)

const { auth } = useAuth<any>()

>Solution :

This:

const AuthContext = createContext({});

Has no information about the type that the context contains. If you provide a default object, then you will get the types you need

const AuthContext = createContext({ auth: '' })

Or pass in a type:

type AuthContextType = {
    auth?: string
}

const AuthContext = createContext<AuthContextType>({})

See playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading