I setup global namespaces for my objects by explicitly setting a property on window
.
window.MyNamespace = window.MyNamespace || {};
Here's how to do it, if you're using TypeScript Definition Manager!
npm install typings --global
Create typings/custom/window.d.ts
:
interface Window {
MyNamespace: any;
}
declare var window: Window;
Install your custom typing:
typings install file:typings/custom/window.d.ts --save --global
Done, use it! Typescript won't complain anymore:
window.MyNamespace = window.MyNamespace || {};
Using TSX? None of the other answers were working for me.
Here's what I did:
(window as any).MyNamespace
Create a file called global.d.ts
e.g /src/@types/global.d.ts
then define an interface like:
interface Window {
myLib: any
}
ref: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-d-ts.html
I don't need to do this very often, the only case I have had was when using Redux Devtools with middleware.
I simply did:
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
Or you could do:
let myWindow = window as any;
and then myWindow.myProp = 'my value';
After finding answers around, I think this page might be helpful. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation Not sure about the history of declaration merging, but it explains why the following could work.
declare global {
interface Window { MyNamespace: any; }
}
window.MyNamespace = window.MyNamespace || {};
I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.
In order for my library to use declarations I had to use the d.ts
extention for the file that declares the new properties of the global object.
So in the end, the file ended up with something like:
/path-to-angular-workspace/angular-workspace/projects/angular-library/src/globals.d.ts
Once created, don't forget to expose it in your public_api.ts
.
That did it for me. Hope this helps.