What means "ambient" in TypeScript

The english word

Ambience : the character and atmosphere of a place..

TypeScript version

TypeScript declaration files exist to tell the compiler of the environment in which it is running. Hence the word ambient context. You can only do declarations in a declaration context and not implementations.

E.g. if you have some awesomeLibrary declared in a raw JS file that TypeScript does not know about the following will error:

awesomeLibrary = 123; // Error: `awesomeLibrary` is not defined

So you can declare it in an ambient context and now TypeScript will be fine:

declare var awesomeLibrary: any;
awesomeLibrary = 123; // allowed

More

More on ambient declarations.


Ambient simply means "without implementation".

Ambient declarations only exist in the type system and are erased at run-time:

// ambient module declaration
declare module "mymod" { /*... */ }

// ambient namespace declaration
declare namespace MyNamespace { /*... */ }

// ambient variable declaration
declare const myVar: string;

For example declare const myVar: string is like a promise to the compiler: "Assume that there will be a const myVar with type string defined at run-time" (other cases analogue).

You also can think of ambient as the declare keyword in TS. All type declarations like interfaces or type aliases are implicitly ambient by definition, as it is clear for the compiler, that these have no run-time impact.

declare type MyType = {a: string} // is valid
type MyType = {a: string} // shorter, so just leave "declare" out

"A function implementation cannot be declared in an ambient context."

As said, ambient declarations cannot contain run-time code, like:

declare module "mymod" {
    function foo() { // error: An implementation cannot be declared in ambient contexts.
        console.log("bar")
    }
}

Given "mymod" is a npm package, the implementation code would rather be in the main .js file under "node_modules/mymod", and above types reside in a separate .d.ts file.

Tags:

Typescript