Global-modifying Modules

A global-modifying module alters existing values in the global scope when they are imported. For example, there might exist a library which adds new members to String.prototype when imported. This pattern is somewhat dangerous due to the possibility of runtime conflicts, but we can still write a declaration file for it.

Identifying global-modifying modules

Global-modifying modules are generally easy to identify from their documentation. In general, they’re similar to global plugins, but need a require call to activate their effects.

You might see documentation like this:

  1. // 'require' call that doesn't use its return value
  2. var unused = require("magic-string-time");
  3. /* or */
  4. require("magic-string-time");
  5. var x = "hello, world";
  6. // Creates new methods on built-in types
  7. console.log(x.startsWithHello());
  8. var y = [1, 2, 3];
  9. // Creates new methods on built-in types
  10. console.log(y.reverseAndSort());

Here is an example

  1. // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
  2. // Project: [~THE PROJECT NAME~]
  3. // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
  4. /*~ This is the global-modifying module template file. You should rename it to index.d.ts
  5. *~ and place it in a folder with the same name as the module.
  6. *~ For example, if you were writing a file for "super-greeter", this
  7. *~ file should be 'super-greeter/index.d.ts'
  8. */
  9. /*~ Note: If your global-modifying module is callable or constructable, you'll
  10. *~ need to combine the patterns here with those in the module-class or module-function
  11. *~ template files
  12. */
  13. declare global {
  14. /*~ Here, declare things that go in the global namespace, or augment
  15. *~ existing declarations in the global namespace
  16. */
  17. interface String {
  18. fancyFormat(opts: StringFormatOptions): string;
  19. }
  20. }
  21. /*~ If your module exports types or values, write them as usual */
  22. export interface StringFormatOptions {
  23. fancinessLevel: number;
  24. }
  25. /*~ For example, declaring a method on the module (in addition to its global side effects) */
  26. export function doSomething(): void;
  27. /*~ If your module exports nothing, you'll need this line. Otherwise, delete it */
  28. export {};