I'm currently writing my code in TypeScript, and I'm not using a library like Webpack to bundle the code. I've set the declaration flag to true in my tsconfig.json to ask TypeScript to generate declarations for the code. I'm making a class accessible on the window object for external scripts to make use of, and I'm currently doing so with the following code (Foo.ts):
(() => {
class Foo {
// ...
}
(window as any).Foo = Foo;
})();
When transpiled into JavaScript, this works and the Foo class can be found on the window object. However, the declaration file (Foo.d.ts) contains nothing.
I assumed that this was because the file wasn't exporting anything, so I changed the code to export the variable (and place it in the top-level rather than in a closure) and it worked. However, specific to my use case, it made no sense to "export" a variable when the script is going to be loaded in the browser (of course, unless I used something like Webpack).
This is so far preventing me referencing the class type in integration tests. I can't simply declare the variable for use either since it would require writing my own d.ts file (which defeats the purpose of just using TypeScript) nor can I declare it midway through my existing Foo.ts file since TypeScript does not allow non-top-level declares. It wouldn't make sense for me to add in Webpack to the toolchain and add more bloat to a small script that doesn't use any dependencies either.
I've actually run into this same issue trying to get types for oojs-ui, which does the same thing. Unfortunately, I'm not as keen to simply set window.Foo to any in my tests and hope for the best.
How can I have TypeScript emit the declaration for the Foo class, without needing an export statement? In other words, how can I have TypeScript export declarations for a class appended to the window variable?
I suspect what you're missing is module augmentation in the global namespace. If you add your class definition in the way described in this answer does it resolve your issue?
Something like playground