My understanding of TypeScript is that the example code provided does not actually generate or modify any JavaScript output. Instead, it consists of declarations that serve to assist in error checking by IntelliSense and the TypeScript compiler, without directly impacting the code itself. These declarations are meant for an "ambient" declaration file, which provides TypeScript definitions for regular JavaScript libraries, enabling TypeScript and IntelliSense to work with them as if they were native TypeScript files rather than plain JavaScript. When TypeScript encounters something without a corresponding declaration, it typically treats it as an "any" type.
For the mentioned library, it is recommended to utilize the existing type library (npm install --save-dev @types/d3
). After installing both the library (npm install --save d3
) and its types @types/d3
, using import * as d3 from 'd3'
in a .ts file (in Angular 5; other setups may vary) successfully brings in the object and type information. The contents of the types file will differ significantly from those in the TypeScript documentation example, but they all consist of declarations rather than executable code.
Regarding the edits
The file in question is not a primary TypeScript file but a declarations file outlining the "TypeScript shape" of a standard JavaScript library - essentially guiding how the TypeScript compiler and IntelliSense should interpret the structure of the JavaScript code if it were written in TypeScript. Despite appearances, the choice of naming it D3 was intentional. The .d.ts
file aims to offer TypeScript metadata for a library like D3 (https://www.npmjs.com/package/d3) which lacks its own TypeScript information (though such details are available through the @types package).
If constructing your own library code and desiring to operate within a namespace akin to the validation example, you would use namespace D3
instead of declare namespace D3
, while working in a .ts
file rather than a .d.ts
one. The first part of the documentation illustrates using namespaces within your TypeScript code, while the latter demonstrates providing TypeScript metadata for pure JavaScript code.