Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are ambient declarations

Tags:

typescript

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 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?

like image 570
Max Koretskyi Avatar asked Dec 01 '16 16:12

Max Koretskyi


People also ask

What are ambient files?

In Typescript, Ambient in refers to the declarations used to inform a compiler that the actual piece of code exists in a different place. For example, a developer might want to write a third-party library in plain JS using jQuery or Angular.

Is it possible to generate TypeScript declaration files from JS library?

With TypeScript 3.7, TypeScript added support for generating . d. ts files from JavaScript using JSDoc syntax. This set up means you can own the editor experience of TypeScript-powered editors without porting your project to TypeScript, or having to maintain .


1 Answers

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"); }
like image 156
Nitzan Tomer Avatar answered Oct 03 '22 01:10

Nitzan Tomer