Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 546
George Avatar asked Oct 20 '25 04:10

George


2 Answers

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

like image 120
Poku Avatar answered Oct 21 '25 16:10

Poku


Try

(window as any).UndeclaredExportedProperty.aFunction()

this will tell the compiler to temporarily treat the Window instance as untyped and allow you to do anything with it.

like image 30
Andrew Eisenberg Avatar answered Oct 21 '25 16:10

Andrew Eisenberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!