TypeScript ยท Chapter 38 of 44

TypeScript Declaration Files

Declaration files, ending in `.d.ts`, contain only type information without any actual implementation code. They let TypeScript understand the shape of JavaScript code, including third-party libraries.

Many popular JavaScript libraries ship their own .d.ts files, or have community-maintained ones available through the DefinitelyTyped project, installed via packages like `@types/library-name`.

Syntax
declare function greet(name: string): string;

What's inside a .d.ts file

A declaration file contains type declarations like interfaces, type aliases, and function signatures, using the `declare` keyword for values that exist elsewhere at runtime.

Using @types packages

For JavaScript libraries without built-in types, you can often install community type definitions with `npm install --save-dev @types/library-name`, giving you full type checking and autocomplete.

Example 1 (typescript)
// greet.d.ts
declare function greet(name: string): string;
Output
(no runtime output โ€” a declaration file)

This declares that a greet function exists elsewhere, describing its type signature only.

Example 2 (bash)
npm install --save-dev @types/lodash
Output
added 1 package

Installs community-maintained type definitions for the lodash library so TypeScript understands its API.

Key points

  • Declaration files end in .d.ts and contain only type information.
  • They let TypeScript type-check plain JavaScript libraries.
  • The `declare` keyword describes values that exist without providing implementation.
  • @types packages provide community-maintained types for popular JS libraries.
๐Ÿ’ก Note: You rarely need to write .d.ts files by hand unless you're publishing a library or typing an untyped dependency.

๐Ÿ“ Quick Quiz

1. What file extension do declaration files use?

2. What do declaration files contain?

3. How do you get type definitions for an untyped JS library?