Search code examples
typescriptnamespacesambient

Ambient Namespaces typescript example


The Namespaces chapter give an example related to D3.d.ts which I don't understand.
This is the full example:

declare namespace D3 {
    export interface Selectors {
        select: {
            (selector: string): Selection;
            (element: EventTarget): Selection;
        };
    }

    export interface Event {
        x: number;
        y: number;
    }

    export interface Base extends Selectors {
        event: Event;
    }
}

declare var d3: D3.Base;

What I really don't understand is how would I use D3.d.ts in my modules or my typescript scripts? Please give me some short examples.

EDIT
Please ignore the fact that here it is used D3; could be B3 or G3 or X7 ... whatever; I'm not interested on a specifically library. I'm only interested in how would I use the example given both in my typescript modules and my typescript scripts.

EDIT2 What mostly confuse me is the fact that the above example uses declare namespace ... instead of namespace D3 (as used e.g. for namespace Validation). Also what's the use (and how to use?) of declare var d3: D3.Base;?


Solution

  • Such declarations define global variables that do not come from imports but might be defined on the window by some <script>. To be able to simply use these variables directly (without imports!) you could always use a reference, e.g.:

    /// <reference path="../types/D3.d.ts" />
    d3.select("div"); // No import!
    

    If the declaration file is placed in an @types directory it should be included without explicit reference.


    The namespace uses declare because this is a declaration file: It has to either export the namespace (which only is valid for modules) or declare it, to make these types available.