Search code examples
typescripttypescript1.6

TypeScript, declare a variable vs. declare a module


TL;DR

What does it mean when a variable is declared in typescript? For example (from the TypeScript handbook or wiki):

declare var d3: D3.Base;

What is the purpose in this case?

More thoughts:

I understand that declaring a module or namespace indicates that it is ambient, i.e. it is not compiled into JavaScript and is only used for describing the shape of objects (type checking). However, the purpose of variable declaration eludes me.

The question arose as I was looking at the angular declaration file from definitely typed (angular.d.ts):

declare var angular: angular.IAngularStatic;

// Support for painless dependency injection
interface Function {
    $inject?: string[];
}

// Collapse angular into ng
import ng = angular;
// Support AMD require
declare module 'angular' {
    export = angular;
}

///////////////////////////////////////////////////////////////////////////////
// ng module (angular.js)
///////////////////////////////////////////////////////////////////////////////
declare module angular {......module declaration continues....

I'm struggling to figure out exactly what's going on here with the "import" and variable declaration. Visual Studio Code doesn't seem to like the import, but Visual Studio 2015 accepts it (both use TypeScript 1.6.2).


Solution

  • What is the purpose in this case

    Ambient Declarations. Primarily to support libraries (and environment variables like window) that are not written in TypeScript.

    More : https://basarat.gitbooks.io/typescript/content/docs/types/ambient/intro.html

    However, the purpose of variable declaration eludes me.

    Some libraries provide a global variable. E.g. $ by jquery.

    This topic is covered here : https://basarat.gitbooks.io/typescript/content/docs/types/ambient/variables.html

    I'm struggling to figure out exactly what's going on here with the "import" and variable declaration

    import can be used to copy the type (here declare module angular).

    This is covered in the tips section here : https://basarat.gitbooks.io/typescript/content/docs/project/declarationspaces.html