33

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.

2 Answers 2

40

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.

24

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.

1
  • I think this is the more correct answer. The accepted answer does have lots of useful information on type declaration in general, but implies that type erasure only applies to ambient types which is not true. Aug 1, 2021 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.