I setup global namespaces for my objects by explicitly setting a property on window
.
window.MyNamespace = window.MyNamespace || {};
For reference (this is the correct answer):
Inside a .d.ts
definition file
type MyGlobalFunctionType = (name: string) => void
If you work in the browser, you add members to the browser's window context by reopening Window's interface:
interface Window {
myGlobalFunction: MyGlobalFunctionType
}
Same idea for NodeJS:
declare module NodeJS {
interface Global {
myGlobalFunction: MyGlobalFunctionType
}
}
Now you declare the root variable (that will actually live on window or global)
declare const myGlobalFunction: MyGlobalFunctionType;
Then in a regular .ts
file, but imported as side-effect, you actually implement it:
global/* or window */.myGlobalFunction = function (name: string) {
console.log("Hey !", name);
};
And finally use it elsewhere in the codebase, with either:
global/* or window */.myGlobalFunction("Kevin");
myGlobalFunction("Kevin");
Just found the answer to this in another StackOverflow question's answer.
declare global {
interface Window { MyNamespace: any; }
}
window.MyNamespace = window.MyNamespace || {};
Basically you need to extend the existing window
interface to tell it about your new property.
Make a custom interface extends the Window and add your custom property as optional.
Then, let the customWindow that use the custom interface, but valued with the original window.
It's worked with the typescript@3.1.3.
interface ICustomWindow extends Window {
MyNamespace?: any
}
const customWindow:ICustomWindow = window;
customWindow.MyNamespace = customWindow.MyNamespace {}
AS OF TYPESCRIPT ^3.4.3 THIS SOLUTION NO LONGER WORKS
Or...
you can just type:
window['MyNamespace']
and you wont get a compile error and it works the same as typing window.MyNamespace
Using
window["MyNamespace"] = window["MyNamespace"] || {};
should be alright as using string property, but if you really want to have a separated window and organised your code, you can extends window object:
interface MyNamespacedWindow extends Window {
MyNamespace: object;
}
declare var window: MyNamespacedWindow;
If you need to extend the window
object with a custom type that requires the use of import
you can use the following method:
window.d.ts
import MyInterface from './MyInterface';
declare global {
interface Window {
propName: MyInterface
}
}
See 'Global Augmentation' in the 'Declaration Merging' section of the Handbook: https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation