In TypeScript, why do you sometimes need to use declare for declaring a variable, and sometimes you don't (the same question is true for functions, …)?
To give an example: When (and why) do I use
declare var foo: number;
if
let foo: number;
would do the same (at least it seems to me as if it did the same, i.e. they both declare a variable called foo of type number). What's the difference?
You never use declare to declare a variable. You just use it to let TypeScript know that the variable exists, even though it's not declared in the code (for instance, because it's a global declared in other code, or because you're going to combine the JavaScript output of tsc with another file that declares the variable). Or put it another way: It only declares it for the TypeScript compiler, not for the JavaScript runtime.
If you use the playground to compile your declare var foo: number;, it literally outputs nothing for that declaration; example.
In contrast, let foo: number; (or var foo: number;) is a variable declaration; example.
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