Advanced TypeScript

Declaration Files & Ambient Types

Declaration files describe the types of JavaScript code to TypeScript. Ambient declarations tell TypeScript about values, globals, or modules that exist at runtime but are not defined in the current TypeScript source.
  • .d.ts files contain types only
  • Declarations can type JavaScript libraries
  • declare means 'trust me, this exists at runtime'
  • Module declarations bridge untyped packages
  • Bad declarations create confident bugs
Ambient module declaration
declare module "legacy-parser" {
  export function parse(input: string): unknown
}

declare const __APP_VERSION__: string
These declarations tell TypeScript about runtime values supplied elsewhere.
Declaration concepts
ConceptMeaningExample
.d.tsType declarationsindex.d.ts
declare moduleDescribe external modulelegacy package
declare globalAugment global scopewindow flags
@types packageCommunity declarations@types/node
types fieldPackage declaration entrypackage.json
Sources
  • The TypeScript HandbookDeclaration Files
  • TypeScript ReferenceModules .d.ts
  • Effective TypeScript, 2nd EditionType declarations