In TypeScript, "declare var foo: number;
" means: "In the code there is a number called foo. I know that you would not retrieve it. But please trust me and act just like you know it." It is a kind of forward declaration just like you can see it in C/C++.
Example:
Assume that you are writing a TS script using jQuery. You would include all the JavaScript like this somewhere in your HTML page:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="myscript.js"></script> <!-- generated from TypeScript, with something like "tsc myscript.ts" -->
As a consequence, there is no need to include jQuery in your TS script, since JS generated from your TS script will know everything about jQuery's stuff. However, the TS transpiler will remark jQuery's iconic "$()
" a bunch of time in your code. You do not include jQuery in your TS code (because there is no need to) so it does not know anything about "$()
". It will consequently report to you lots of errors asking you what the hell is this "$
" it sees everywhere in the code. To solve all those $
-related errors, you will write "declare var $: jQuery;
" at the beginning of your TS script. By writing this, you tell this to the TS transpiler:
In the code there is a variable called "$
" whose type is "jQuery
". I know that you would not have retrieved it. But assume that it exists and please act like there was a "import "aTSfile.ts";
" which perfectly describes it to you (a description just like I use it) earlier in the code. Trust me, JavaScript will know what that "$
" REALLY is when the script is executed. Do not worry about that. ;-)