Search code examples
reactjstypescriptreact-typescript

Property 'X' does not exist on type 'context | null'. ts(2339)


I can't figure this out. Why is TypeScript showing this error even though I have defined the type of the function in the type TasksContextType...

Error: Property 'addTask' does not exist on type 'TaskContextType | null'. ts(2339)

Component file using the addTask function:

const { addTask } = useTasks();

addTask function:

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

Type declaration:

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

The TasksContext itself:

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

EDIT: useTasks(); Hook:

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

Solution

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

    Your default value is null, and its type is possibly null, so you would need to narrow down the type first.

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