Search code examples
javascripttypescriptwebpackecmascript-6ecmascript-2016

Typescript - How to avoid compilation error from undeclared objects


Assuming I have an external javascript inserted in the page and it exports a few things to the external scope (ie binds them to window).

I want to call some of those properties in my typescript projects as:

UndeclaredExportedProperty.aFunction()

But typescript will not allow me to compile that ><

I don't want to go through a convoluted way of declaring the whole interface of the module since I don't know it and quite frankly I don't care about it. Its just a module that I have to call once and "trust" that by the time I make the call its loaded and contains the correct elements (its non critical so not calling it will not make the world catch fire).

What is the easiest way of doing this with typescript ?

Edit in response to mark as duplicate:

Whilst the answer to that question did solve my problem the question is different (for example stack isn't able to find it as a duplicate suggestion) and I feel like for what I'm trying to do Pokus answer is a more straight forward and general solutions than the answers in that question

That being said, if an admin feels like this is still a duplicate or to simple of a question feel free to delete/close since I've gotten my answer. Personally I will leave it standing because the next person searching via google or so might find an answer more easily this way.


Solution

  • You should use the declare keyword for that:

    declare var UndeclaredExportedProperty: any;
    

    The official docs states this here: https://www.typescriptlang.org/docs/handbook/modules.html in the section Working with Other JavaScript Libraries