Search code examples
reactjsreact-context

Using object in ReactJS Context - method in object causes Property 'myMethod' does not exist on type 'unknown'


I am trying to use a context for the first time where I have a Reactjs library which creates the context, and then in the main app updates the context and passes as a context provider within app.js.

In my library I have the following:

import * as React from "react";

export const MyContext = React.createContext(null);

export const MyContextProvider = MyContext.Provider;
export const MyContextConsumer = MyContext.Consumer;

export class MyClass
{
    constructor()
    {
        ....
    }

    ...

    myMethod(param1, param2 = null)
    {
        ...
    }

Then in my main project inside app.tsx I have the following:

const my_class = new MyClass();
my_class.initialise("param1", "param2", "param3");

<MyContextProvider value={my_class}>
          <ErrorBoundary>
              <BrowserRouter>
                  <Routes>
                      <Route index element={<Home />} />
                      <Route path='/blog' element={<BlogHome />} />
                      <Route path='/blog/:slug' element={<BlogPost />} />
                      <Route path='*' element={<NotFound />} />
                  </Routes>
              </BrowserRouter>
          </ErrorBoundary>
      </MyContextProvider>

Then in my child component in this case the NotFound component I then do the following:

const my_class = useContext(MyContext);
console.log("My class context", my_class);
my_class.myMethod(err, "Low");

This fails to compile as method myMethod throws an error Property 'myMethod' does not exist on type 'unknown'

When I remove the call to myMethod and just print my_class the object has everything that's been passed into the constructor, and I can see the method in there although it's within a [[Prototype]] object but not sure if that's expected or whether I should reference that in some way to access the method call.


Solution

  • I figured the issue was caused by a typescript issue within my main project.

    Where I had const my_class = useContext(MyContext) I had to set the type of my_class by doing const my_class : MyContext = useContext(MyContext) resolves the issue