I have come across some code like this:
declare type A = { ... };
declare interface B { ... }
From searching for the declare
keyword (and none of the hits pointed to me the TypeScript docs for some reason), declare
is used when a variable exists in JavaScript and you need to reference it from TypeScript, so you declare to the compiler that this variable indeed exists.
All examples I have found that use this keyword use it like this: declare var a;
Why would I ever use it in front of a type
or interface
? Based on my understanding of declare
, it is completely useless to do so, but the compiler doesn't give me any errors.
The declare keyword in TypeScript is used for the Ambient declaration of variables or for methods. Ambient Declarations is like an import keyword. Which tells the compiler that the source exists in another file.
declare is used to tell the compiler "this thing (usually a variable) exists already, and therefore can be referenced by other code, also there is no need to compile this statement into any JavaScript". Common Use Case: You add a reference to your web page to a JavaScript file that the compiler knows nothing about.
The interface declaration declares various attributes about the interface, such as its name and whether it extends other interfaces. The interface body contains the constant and the method declarations for that interface. The StockWatcher interface and the structure of an interface definition.
declare class is for when you want to describe an existing class (usually a TypeScript class, but not always) that is going to be externally present (for example, you have two . ts files that compile to two . js files and both are included via script tags in a webpage).
Looks like I just found out why.
From this github issue:
declare
should be optional on type aliases and interfaces.
declare type
anddeclare interface
are identical totype
andinterface
Since we already shipped type aliases this way, people have had to write
declare type
a bunch of times. We could break them and say "Writetype
, notdeclare type
", but that would be a massive break for no real reason.
In summary, there is no reason to use declare
for types and interfaces.
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