如何创建一个在 Typescript 中有引用的上下文?

How can I create a Context that has a reference inside in Typescript?

我正在尝试使用 Typescript 在 React Native 中创建一个内部有引用的上下文,但是,我遇到了各种类型错误,而且我似乎无法修复它。我希望它默认为 null,但我做不到。

const WebContext: RefObject<WebView<{}>> | null = createContext(null);

它引发了这个错误:Property 'current' is missing in type 'Context<null>' but required in type 'RefObject<WebView<{}>>'.

我做错了什么?我怎样才能将它初始化为 null,同时能够稍后将它的值设置为 WebView 的引用?

请注意,WebContext 的类型应该是 Context<RefObject<WebView<{}>> | null> 而不是 RefObject<WebView<{}>> | null,但这仍然会导致类型错误,因为 createContext(null) 会产生类型 Context<null>。您可以通过向 createContext 调用提供通用参数 RefObject<WebView<{}>> | null 来扩展上下文类型:

const WebContext = createContext<RefObject<WebView<{}>> | null>(null);
// WebContext: Context<RefObject<WebView<{}>> | null>

TypeScript playground