ASfdsa33
ASfdsa33

Reputation: 97

adding property to javascript object in typescript without errors

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 ?

Upvotes: 1

Views: 2628

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

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.

Upvotes: 1

Related Questions