【问题标题】:Property 'X' does not exist on type 'context | null'. ts(2339)类型 \'context | 上不存在属性 \'X\'无效的\'。 ts(2339)
【发布时间】:2022-11-08 17:22:49
【问题描述】:

我想不通。即使我在 TasksContextType 类型中定义了函数的类型,为什么 TypeScript 仍显示此错误...

错误:'TaskContextType | 类型不存在属性'addTask'无效的'。 ts(2339)

使用 addTask 函数的组件文件:

const { addTask } = useTasks();

添加任务功能:

const addTask = async (title: string) => {
    const taskRef = await addDoc(tasksCollection, {
      title,
      desc: "",
      completed: false,
    });
  };

类型声明:

export type TaskContextType = {
  tasks: ITask[];
  addTask: (title: string) => Promise<void>;
};

TasksContext 本身:

const TasksCtx = createContext<TaskContextType | null>(null);

编辑:使用任务();钩:

export const useTasks = () => useContext(TasksCtx);

【问题讨论】:

  • 你能显示 useTasks() 钩子的定义吗?我想我知道问题出在哪里,但我需要看一下 useTasks() 的定义来确认我的假设。
  • 正如所料,这正是@Yuji 'Tomita' Tomita 刚刚回答的内容。

标签: reactjs typescript react-typescript


【解决方案1】:

const TasksCtx = createContext&lt;TaskContextType | null&gt;(null);

您的默认值为 null,其类型可能为 null,因此您需要先缩小类型。

const context = useContext(...)
if (context !== null) {
   context.addTask
}

【讨论】:

    【解决方案2】:

    尝试添加一个空检查器。 上下文?.addTask

    【讨论】:

      【解决方案3】:

      对我来说,解决方案是让createContext() 没有参数

      const TasksCtx = createContext();
      

      【讨论】:

        猜你喜欢
        • 2021-01-10
        • 2019-08-11
        • 2021-08-02
        • 2020-06-02
        • 2022-07-09
        • 2022-10-04
        • 2023-02-07
        • 2020-08-23
        • 2021-12-19
        相关资源
        最近更新 更多