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

Time:07-15

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)

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>()

CodePudding user response:

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

  • Related