I've heard of loads of different types of classes, but what does an Ambient class do and what exactly is it? How is it different from any other class?
I get this from watching a few videos on typescript, and they are always talking about Ambient classes, but they go on to define just regular old classes, I mean to me, it seems no different from just a normal class with variables and functions in it.
So if one some one can, please define what an ambient class is in a language agnostic context and what does it mean in typescript?
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.
You would get auto-completion after the .
to help you discover the Test
class.
If you already had a whole load of JavaScript that were using from some TypeScript code, you wouldn't get this auto-completion and where you did it would not be type-aware. Rather than re-writing the whole JavaScript file in TypeScript, you can write an ambient declaration for it 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 ambient declaration contains the type information, but not the implementation:
declare module Example {
export class Test {
do() : string;
}
}
This gives you full type-checking and auto-completion for your JavaScript without the need to re-write the whole thing in TypeScript.
When would you do this? Usually you write an ambient declaration when you are consuming a bunch of third-party JavaScript - you can't re-write it in TypeScript every time they update the library, so having an ambient declaration allows you to take the updates with minimal impact (you may have to add new features, but you never have to make changes due to implementation details). The ambient declaration acts as a contract that states what the third-party library does.
You can find out more by reading my guide to writing ambient declarations, and you can find a lot of existing ambient declarations for popular JavaScript libraries on Definitely Typed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With