🔷 TypeScript Intermediate

What are ambient declarations in TypeScript?

Answer

Ambient declarations tell the TypeScript compiler about the shape of JavaScript code that exists at runtime but was not written in TypeScript. They use the declare keyword without providing an implementation. declare var __VERSION__: string; — tells TS that a global variable exists. declare function require(module: string): any;. declare class Animal { name: string; }. declare module "lodash" { export function chunk<T>(array: T[], size: number): T[][]; }. Ambient declarations are placed in .d.ts declaration files (type definition files). They have no runtime equivalent — the compiler uses them for type checking but emits nothing. The @types organization on npm publishes community-maintained declaration files for popular JavaScript libraries (@types/react, @types/node, etc.). declare global { interface Window { myProp: string; } } augments the global scope. The typeRoots and types tsconfig options control which type declarations are included.