Lesson 30 +10 XP

Type Definitions (.d.ts) & DefinitelyTyped

Declaration Files (.d.ts) & DefinitelyTyped

Declaration files (.d.ts) provide type annotations for JavaScript code without containing executable code.

Ambient Declarations (declare)

Use the declare keyword to tell TypeScript that a variable or library exists externally (e.g. via CDN script tag).

// global.d.ts
declare const API_URL: string;
declare function trackEvent(eventName: string): void;

DefinitelyTyped & @types Packages

Many popular npm packages written in JavaScript lack built-in TypeScript types. The community provides types via the DefinitelyTyped repository hosted under the @types npm scope.

To install type definitions for libraries like Express or Lodash:

npm install --save-dev @types/express
npm install --save-dev @types/lodash

Authoring Module Declarations

// my-legacy-lib.d.ts
declare module "my-legacy-lib" {
  export function calculateHash(input: string): string;
  export const version: string;
}

TL;DR

  • .d.ts files contain type declarations without runtime JavaScript code.
  • Use declare to describe ambient variables from global scripts or legacy libraries.
  • Install community types using npm install -D @types/<package-name>.