I have experience building APIs and applications in ES2015, but I am still learning the best practices for TypeScript. Can someone assist me with this challenge? Suppose I am creating an API/SDK for a shop. The objective is for the user to include my js file and access the shop and its namespaces through the window object, similar to how it can be done with Angular and other libraries.
window.shop.init();
window.shop.cart.get();
window.shop.cart.set();
window.shop.cart.clear();
In ECMAScript 2015, I would define methods like get
and set
, import them into my main file, extend the shop object, and then the global object as well.
// in my cart.js namespace file
export {get} from './get';
// in my shop.js
import * as cart from './cart';
global.shop = {
cart
}
While this approach works well for namespacing in ES2015, it doesn't feel quite right in TypeScript due to all the module and namespace keywords.
I am looking to achieve the same outcome in TS. I have tried various approaches, but none have been successful so far.
module shop {
export const cart = {...}
}
(<any>window).shop = shop;
or
namespace shop {
// ...
}
(<any>window).shop = shop;
Some tutorials suggest that a module is automatically attached to the global/window object, but I have not experienced that. Any help on this issue would be greatly appreciated!