如何使用 React TypeScript 修复“{}”上不存在的 属性?

How to fix property does not exist on '{}' with react typescript?

我正在尝试使用 typescript 为我的 ReactJS 应用程序全局创建一个 登录状态 . 我在文件中声明了上下文并导入到 App.tsx 文件。

export const loginContext = createContext({});

在 App.tsx 文件中,我创建了一个状态并将变量和函数作为对象提供。

import { loginContext } from "./context";

const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
    <loginContext.Provider value={{ isLoggedIn, setIsLoggedIn }}>
    ...
    </loginContext.Provider>
)

现在我想访问另一个文件中的 isLoggedIn 变量

我试图通过写作来做到这一点,

import { loginContext } from "../context";

const { isLoggedIn, setIsLoggedIn } = React.useContext(loginContext);

但是 typescript 向我显示以下错误,

Property 'isLoggedIn' does not exist on type '{}'.

Property 'setIsLoggedIn' does not exist on type '{}'.

任何帮助将不胜感激

您应该在创建上下文的地方定义适当的默认值。像这样。

export const loginContext = createContext({
 isLoggedIn: false,
 setIsLoggedIn: (value: boolean): void => {}
});