Maximus Maximus - 8 days ago 5
TypeScript Question

What is ambient declarations

I've been seeing a lot using articles mentioning

ambient declarations
. For example this article. What is it? Can somebody provide an example? Is ambient declaration a declaration of a type created outside existing typescript files but used in these files? Are all declarations ambient?

As I understand
ambient declarations
don't produce any javascript code and are defined using
declare
keyword. Is this the only case of ambient declarations or there are others?

Answer

Yes, ambient declarations let you tell the compiler about existing variable/functions/etc.

For example let's say that in your web page you're using a library that adds a global variable, let's say that it's name is ON_READY and it is a reference to a function.
You need to assign a function to it so you'll do something like:

ON_READY = () => {
    console.log("ready!");
    ...
};

The compiler will complain that:

Cannot find name 'ON_READY'

So you use an ambient declaration to inform the compiler that this variable exists and what it's type is:

declare var ON_READY: () => void;

Now it won't complain about not finding it.


Edit

When using the declare keyword it is always ambient, just like it says in the article you linked to:

The declare keyword is used for ambient declarations where you want to define a variable that may not have originated from a TypeScript file

Non-ambient declarations are just normal variable/function declarations:

let x: number;
const y = "string";
var a = () => { console.log("here"); }