Katsuro Nosuri
Katsuro Nosuri

Reputation: 33

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

Upvotes: 3

Views: 4346

Answers (4)

Jonas
Jonas

Reputation: 11

In the context file:

import { createContext } from "react";

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

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

export default TasksCtx;

then to use the context:

import {useContext} from "react";
import TasksCtx from "../context/TasksCtx";
const context = useContext(TasksCtx);
context?.addTask('string');

Upvotes: 0

Damien Romito
Damien Romito

Reputation: 10055

For me the solution was to let the createContext() without param

const TasksCtx = createContext();

Upvotes: 2

Jesper Karlsson
Jesper Karlsson

Reputation: 1

try adding a nullchecker. context?.addTask

Upvotes: 0

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
}

Upvotes: 0

Related Questions