Typescript: use types for explicit import

1.2k views Asked by At

I'm programming a webextension in Typescript. Since I would like to target both Chrome and Firefox, I need this polyfill.

Importing it looks like this:

import browser from "webextension-polyfill"

Typescript complains could not find a declaration file for webextension-polyfill. But there is an npm module with type definitions: @types/firefox-webext-browser. I have installed this module.

I need the import, since I'm using a bundler to package all this code. If I don't explicitly import the polyfill, the bundler will not pick up the dependency and at runtime, the polyfill is not there (bad in chrome).

This creates a funny situation: Without the import, the typescript compiler automatically picks up the @types package. The code compiles without errors with autocomplete and correct type checking. But at runtime, it doesn't work. On the other hand, with the import, the compiler warns me that he can't find type definitions for the package. The code still compiles, but browser is of type any. So I don't get any autocomplete and static type checking.

My question is: Can I let the package in @types override an import statement ?

1

There are 1 answers

0
Matt McCutchen On BEST ANSWER

@types/firefox-webext-browser declares browser as a global namespace, but your import is shadowing this global declaration. You need to tell TypeScript that the default export of webextension-polyfill is the same as this global namespace. You can do so by creating a separate file declarations.d.ts with the code:

declare module "webextension-polyfill" {
    // Refers to the global `browser` and exports it as the default of `webextension-polyfill`.
    export default browser;
}