React useContext + TS error: "property does not exist on '{}'"

React useContext + TS error: "property does not exist on '{}'"

我设置了一个分发 Firebase 身份验证对象的上下文,如下所示:

export function AuthProvider(props: {children: React.ReactNode}) {
    const [user, setUser] = useState<IUser>({uid: ""});

    useEffect(() => {
        const unsubsribe = firebaseApp.auth().onAuthStateChanged(user => {
            if (user) {
                setUser(user);
                console.log("user: " + user.uid);
            }
        });
        return () => {
            unsubsribe();
        }
    }, [user]);

    const authContextValue = {
        firebaseApp,
        user,
        signOut: () => firebaseApp.auth().signOut(),
        signIn: (email: string, password: string) => firebaseApp.auth().signInWithEmailAndPassword(email, password),
    };

    return (
        <AuthContext.Provider value={authContextValue}>
            {props.children}
        </AuthContext.Provider>
    )
}

export const useAuth = () => React.useContext(AuthContext);

我尝试像这样使用传递的对象:

const {user} = useAuth();
    const {signOut} = useAuth();

导致此错误:Error:(17, 12) TS2339: Property 'user' does not exist on type '{}'.

我知道上下文正在提供对象(它在普通 JS 中工作,在将消费者组件转换为 TS 之前)——那么为什么 TypeScript 认为只传递了 {}(空对象)?在 TypeScript 中使用 useContext 钩子的正确模式是什么?

创建接口并将其分配给您的挂钩:

interface AuthContextType {
  user: IUser;
  signOut: () => void;
  signIn: () => void;
}

export const useAuth = () => React.useContext(AuthContext) as AuthContextType;

这里是小codesandbox to check it out. Also read more about using Typescript with the Context Api here.