🔷 TypeScript Intermediate

What is a declaration file (.d.ts) in TypeScript?

Answer

A declaration file (.d.ts) contains only type information — no implementation code. It describes the shape of JavaScript APIs to TypeScript without rewriting them in TypeScript. Declaration files consist entirely of ambient declarations: declare statements for variables, functions, classes, interfaces, and modules. They are: (1) Generated automatically by the TypeScript compiler when building a library with "declaration": true in tsconfig — alongside the compiled .js output. (2) Hand-written for existing JavaScript libraries. (3) Published to npm as @types/libraryname packages (DefinitelyTyped). When you install @types/react, TypeScript finds the .d.ts files and knows the types of all React APIs. Triple-slash directives (/// <reference types="node" />) reference type packages. .d.ts files enable the TypeScript ecosystem to type-check code that uses any JavaScript library, regardless of whether it was originally written in TypeScript.