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`.
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.
// greet.d.ts
declare function greet(name: string): string;(no runtime output โ a declaration file)This declares that a greet function exists elsewhere, describing its type signature only.
npm install --save-dev @types/lodashadded 1 packageInstalls 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.
