reactjstypescriptreact-typescript

How to refer React type to a React variable in d.ts file namespace


I want to declare a namespace called PluginApi so users can use this d.ts to get code recommendation. In this below code the React is referring to its const React instead of the library React. How do I fix that?

declare namespace PluginApi {
    const React: typeof React
}

Solution

  • There are a few ways to get around this. The easiest way is to import the React module with a different name:

    import ReactModule from "react";
    
    declare namespace PluginApi {
      const React: typeof ReactModule;
    }
    

    TypeScript Playground


    Another option is to refer to the imported module via globalThis to break out of the PluginApi scope.

    import React from "react";
    
    declare namespace PluginApi {
      const React: typeof globalThis.React;
    }
    

    TypeScript Playground