Advertisement
Intermediate TypeScript, Declaration Files

How does the 'declare' keyword work, and what does it promise the compiler?

Short answer

declare tells TypeScript 'trust me, this exists at runtime somewhere else' — it describes a type shape without providing (or requiring) any implementation, and is erased entirely from compiled output.

Save TypeScript mock interview
Advertisement
AModel answer
declare tells TypeScript 'trust me, this exists at runtime somewhere else' — it describes a type shape without providing (or requiring) any implementation, and is erased entirely from compiled output. It's the core keyword used throughout .d.ts files and for describing global variables injected by other scripts.
declare const APP_VERSION: string; // exists globally at runtime, injected by a build tool
console.log(APP_VERSION); // type-checks fine, no import needed
Real-world example
Describing a global variable injected by a bundler's DefinePlugin, or a third-party script tag that attaches to 'window'.
Likely follow-ups
  • What happens if you try to 'declare' something and then also try to assign it a value?
Related topics