Ambient Modules

Ambient Modules

In Node.js, most tasks are accomplished by loading one or more modules. We could define each module in its own .d.ts file with top-level export declarations, but it’s more convenient to write them as one larger .d.ts file. To do so, we use a construct similar to ambient namespaces, but we use the module keyword and the quoted name of the module which will be available to a later import. For example:

node.d.ts (simplified excerpt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
declare module "url" {
  export interface Url {
    protocol?: string;
    hostname?: string;
    pathname?: string;
  }
 
  export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;
}
 
declare module "path" {
  export function normalize(p: string): string;
  export function join(...paths: any[]): string;
  export var sep: string;
}

Now we can /// <reference> node.d.ts and then load the modules using import url = require("url");.

1
2
3
/// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://www.typescriptlang.org");
doc_TypeScript
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.