2

I'm a novice/intermediate user of typescript, so thanks in advance for any patience and assistance.

Chrome/web extensions' content scripts have access to a very limited subset of extension APIs and I'm trying to create a global.d.ts file to reflect that. Here is my [very] busted first attempt:

export {}

declare global {
    interface Window {
        chrome: Chrome
    }
    const chrome: Chrome // I'll ask a question about this line after this code block.
}

interface Chrome {
    runtime: import('../node_modules/@types/chrome/index.d.ts').runtime
    // I know this is bad syntax, and of course, content scripts' chrome.runtime is 
    // only a subset of the full chrome.runtime namespace, but hopefully this
    // illustrates what I'm trying to do.

    // Other namespaces: storage, dom, i18n
}

I've only done a little work with d.ts files before (I have a separate global.d.ts for the extension service worker context). Can anyone help me understand a few things?

  • Does a content-script types library already exist? I didn't see any in DefinitelyTyped.
  • Can a d.ts file "import" a part of another d.ts file? I'd rather not copy/paste/rewrite typings that already exist.
  • Example, how can I declare a global [window.]chrome.runtime.sendMessage and reuse the chrome.runtime.sendMessage from @types/chrome?
  • Conversely to wanting to import parts of @types/chrome, I don't want the rest of the @types/chrome globals/namespaces. @types/chrome/index.d.ts has interface Window { chrome: typeof chrome; } in it.
  • Tangential question: Content scripts run in a DOM context (i.e. globalThis is Window), but I noticed that VSCode won't resolve my global if I only do declare global { interface Window { foo: string } }. I either have to reference the global via window.foo or include a separate global variable like above: declare global { interface Window { foo: string }; const foo: string }. Why doesn't VSCode resolve foo when I added foo to Window?

Thanks again!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.