Search code examples
typescriptdeclare

Is there ever a reason to use the declare keyword in front of types and interfaces?


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.


Solution

  • Looks like I just found out why.

    From this github issue:

    declare should be optional on type aliases and interfaces.

    declare type and declare interface are identical to type and interface

    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 "Write type, not declare 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.