I\'ve been seeing a lot using articles mentioning ambient declarations
. For example this article. What are they? Can somebody provide an example? Is an ambient
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.
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"); }