Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are "Ambient Typings" in the Typescript Typings tool?

Tags:

typescript

I hear the term "ambient" used to describe type definitions downloaded with the typings tool. What does that mean, though?

I can't seem to find a straightforward definition of it or the --ambient flag.

like image 891
Rick Avatar asked Mar 12 '16 04:03

Rick


People also ask

What is ambient in TypeScript?

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.

What is Typings in TypeScript?

Typings was just a tool to install those files. It is now best practice to just use npm. When you have installed those files, which basically only means downloading them and placing them in your project, the TypeScript compiler will understand* that external code and you will be able to use those libraries.


2 Answers

From the TypeScript docs:

An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable. For example, by default the TypeScript compiler will print an error for uses of undefined variables. To add some of the common variables defined by browsers, a TypeScript programmer can use ambient declarations.

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#1.1

To put it a little more simply. Ambient declarations tell the TypeScript compiler that when the JavaScript is executed, something will exist that the TypeScript compiler can't see right now (Because it isn't TypeScript).

Imagine if you are writing code that uses jQuery. If you just try to write $() TypeScript will think you are using an undeclared variable $ and will throw an error. Ambient declarations like declare var $ tell the TS compiler that, even though $ isn't visible to the compiler, it will exist when the JS is executed.

like image 77
Ted A. Avatar answered Oct 26 '22 23:10

Ted A.


From typings v1.0.0 release, the unclear term ambient has been changed to global.

You can simply think these type definitions are "global" to the project.

like image 34
tan9 Avatar answered Oct 27 '22 00:10

tan9