stackademic

The leading education platform for anyone with an interest in software development.

TypeScript Declaration Files

Author .d.ts files to describe types for JavaScript and ambient modules

Overview

Declaration files (.d.ts) contain only type information—no runtime code—and describe the shape of JavaScript libraries, global variables, or module APIs. TypeScript consumes them to type-check code that imports untyped packages or interacts with globals. Bundled libraries ship their own; for others you write or install ambient declarations.

Syntax / Usage

Use declare to describe things that exist at runtime but have no TypeScript source. Module and global augmentation extend existing types.

// globals.d.ts — describe a runtime-injected global
declare global {
  interface Window {
    analytics: {
      track(event: string, props?: Record<string, unknown>): void
    }
  }
}

// Declare the shape of an untyped module
declare module "legacy-math" {
  export function add(a: number, b: number): number
  export const PI: number
}

// Needed so the file is treated as a module
export {}

Examples

Provide types for a module that only ships JavaScript.

// slugify.d.ts
declare module "slugify" {
  interface Options {
    lower?: boolean
    strict?: boolean
  }
  function slugify(input: string, options?: Options): string
  export = slugify
}

Let non-code imports type-check by declaring wildcard modules.

declare module "*.svg" {
  const content: string
  export default content
}

Augment an existing library's types without forking it.

import "express"

declare module "express" {
  interface Request {
    userId?: string
  }
}

Common Mistakes

  • Adding runtime code to a .d.ts file, which is not allowed
  • Forgetting export {}, so declare global is not applied
  • Using export default where the JS uses CommonJS export =
  • Redeclaring types that the package already ships, causing conflicts
  • Placing .d.ts files outside the include paths in tsconfig.json

See Also

interfaces typescript-decorators basic-types