-1

I have a web extension that applies a custom object on the window object like:

window.extensionName // { method1: () => {} }

However in my TypeScript files, when I reference window.extensionName, I get this error:

Property 'extensionName' does not exist on type 'Window & typeof globalThis'.

But it does in fact exist on the window object because it was added by the extension. How do I make TypeScript stop complaining about this?

And is there a way to specify the new object's type globally for my whole project so that TypeScript can use autocomplete?

sdfsdf
  • 5,052
  • 9
  • 42
  • 75

2 Answers2

0

You can use declare var to declare that extensionName exists on globalThis (documentation).

declare var extensionName: { method1: () => {} };

window.extensionName.method1 = () => {
  return {};
}

Demo

Ryan Pattillo
  • 331
  • 1
  • 8
  • I pasted your example in a `.tsx` file and got `Property 'extensionName' does not exist on type 'Window & typeof globalThis'` – sdfsdf Jul 20 '22 at 00:39
  • @sdfsdf, then can you update the question to show enough code to reproduce the issue? Preferably through a link like David and I have in our answers. – Ryan Pattillo Jul 20 '22 at 00:54
-1

You can extend the definition of Window via declaration merging.

This does not produce an error:

interface Window {
  extensionName: {
    method1: () => {}
  }
}

window.extensionName.method1 = () => {
  return {};
}

TypeScript Playground demonstrating this technique.

David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32
  • I pasted your example in a `.tsx` file and got `Property 'extensionName' does not exist on type 'Window & typeof globalThis'.` – sdfsdf Jul 20 '22 at 00:35