1

I found this article its quite interesting, but it does not help me when I try to extend a global variable like window.

Test.ts

window.test = {}; //ERROR: Property 'test' does not exist on type 'Window'.

(function (test)
{
//do stuff
} (window.test)); //Build: Property 'test' does not exist on type 'Window'

Error message:

ERROR: Property 'test' does not exist on type 'Window'.

How can I solve this ?

1 Answer 1

1

It's called Declaration Merging:

interface Window {
    test(): void;
}

window.test = function() {
    // do what ever
}

(code in playground)

As you can see you need to declare your new method in the Window interface and then the compiler won't complain when you add the actual implementation.

Sign up to request clarification or add additional context in comments.

11 Comments

does it there's something like interface in JS or it's just in typescript ?
@MahmoudZakal interface is a typescript thing: typescriptlang.org/docs/handbook/interfaces.html, as there's no need to such a thing in javascript
As of today there's a kinda-sorta need to do this in JS, if you're using the TS compiler to do type checking using the checkJs option. In that case, the compiler will complain about window.test = ... but is fine with window["test"] = ....
@Coderer Even if you add test to the window interface?
Maybe I misunderstand but in vanilla Javascript there's no such thing as an interface. Mahmoud's question was how to tell the compiler that there should be a .test property on window in Javascript; that's what my comment is about.
|

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.