For example, when you want to work with JavaScript code which extends another library.

  1. import { greeter } from "super-greeter";
  2. // Normal Greeter API
  3. greeter(2);
  4. greeter("Hello world");
  5. // Now we extend the object with a new function at runtime
  6. import "hyper-super-greeter";
  7. greeter.hyperGreet();

The definition for “super-greeter”:

  1. /*~ This example shows how to have multiple overloads for your function */
  2. export interface GreeterFunction {
  3. (name: string): void
  4. (time: number): void
  5. }
  6. /*~ This example shows how to export a function specified by an interface */
  7. export const greeter: GreeterFunction;

We can extend the existing module like the following:

  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 module plugin 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. /*~ On this line, import the module which this module adds to */
  10. import { greeter } from "super-greeter";
  11. /*~ Here, declare the same module as the one you imported above
  12. *~ then we expand the existing declaration of the greeter function
  13. */
  14. export module "super-greeter" {
  15. export interface GreeterFunction {
  16. /** Greets even better! */
  17. hyperGreet(): void;
  18. }
  19. }

This uses declaration merging

The Impact of ES6 on Module Plugins

Some plugins add or modify top-level exports on existing modules. While this is legal in CommonJS and other loaders, ES6 modules are considered immutable and this pattern will not be possible. Because TypeScript is loader-agnostic, there is no compile-time enforcement of this policy, but developers intending to transition to an ES6 module loader should be aware of this.