I am trying to create a context that has a reference inside it in React Native using Typescript, however, I am getting all sorts of type errors and I do not seem able to fix it. I want it to be null by default, but I'm not being able to do it.
const WebContext: RefObject<WebView<{}>> | null = createContext(null);
It is raising this error: Property 'current' is missing in type 'Context<null>' but required in type 'RefObject<WebView<{}>>'.
What am I doing wrong? How could I initialise this to null while being able to set it's value to a reference of a WebView later?
CodePudding user response:
Note that the type of WebContext
should be Context<RefObject<WebView<{}>> | null>
instead of RefObject<WebView<{}>> | null
, but that will still give a type error as createContext(null)
yields a context of type Context<null>
. You can widen the context type by providing a generic parameter RefObject<WebView<{}>> | null
to the createContext
call:
const WebContext = createContext<RefObject<WebView<{}>> | null>(null);
// WebContext: Context<RefObject<WebView<{}>> | null>