Summary:
declare
is a command used to inform the compiler that a certain element, usually a variable, already exists and can be referenced by other code without needing to be compiled into JavaScript.
Typical Scenario:
Imagine you include a JavaScript file in your webpage from an external source like 'foo.com'. This script creates an object with useful methods and assigns it to the identifier 'fooSdk' globally. Your TypeScript code needs to call fooSdk.doSomething()
, but since the compiler is unaware of the existence of the 'fooSdk' variable, it will throw a compilation error.
To resolve this issue, you use the declare
keyword to reassure the compiler that the variable 'fooSdk' does exist with a specific type. While this statement helps the compiler perform static checks on the code, it does not generate any JavaScript output for the declaration.
declare const fooSdk = { doSomething: () => boolean }
Newer versions of TypeScript require a slightly modified syntax:
declare const fooSdk : { doSomething: () => boolean }
You can also apply the declare keyword to class properties to prevent the compiler from emitting any code related to creating those properties. This is useful when your own code handles the property creation, which may not be fully understood by the compiler.
It's worth noting that when declaring types, as opposed to variables, there is no impact on the resulting JavaScript output. Whether there is a practical reason to declare a type remains uncertain.