Ambient declarations are used to provide type information for some existing code.
For example, if you wrote the following in TypeScript:
module Example { export class Test { do() { return 'Go'; } } } var test = new Example.
After . You will get an automatic completion to help you learn the Test class.
If you already had all the JavaScript loading that was used from some TypeScript code, you would not get this autocomplete, and where you did it would not be a type. Instead of rewriting the entire JavaScript file in TypeScript, you can write an ambient declaration instead.
For example, imagine that the following JavaScript file was much larger and would take a long time to re-write in TypeScript:
var Example; (function (Example) { var Test = (function () { function Test() { } Test.prototype.do = function () { return 'Go'; }; return Test; })(); Example.Test = Test; })(Example || (Example = {}));
The environmental declaration contains type information, but not an implementation:
declare module Example { export class Test { do() : string; } }
This gives you complete type checking and autocomplete for your JavaScript without having to rewrite it all in TypeScript.
When will you do it? Usually you write an ambient declaration when you consume a bunch of third-party JavaScript - you cannot rewrite it in TypeScript every time they update the library, so having an ambient declaration allows you to receive updates with minimal ones (you may have to add new functions, but you donβt have to make changes due to implementation details). The environmental statement acts like a contract that states what a third-party library does.
You can find out more by reading my guide to writing ambient ads , and you can find many existing ambient ads for popular JavaScript libraries of a particular type .