问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/49156130/is-there-ever-a-reason-to-use-the-declare-keyword-in-front-of-types-and-interfac