~/
hackweb.dev
TypeScript Declaration Files
Quiz
⌘K
...
~/
/tutorials
/ts/ts-declaration-files/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/ts/13ts-declaration-files
Write
Preview
Diff
# TypeScript Declaration Files Declaration files (`.d.ts`) provide type information for JavaScript code without implementations. ## Basic Structure A declaration file describes the public API of a module: ```typescript // logger.d.ts export function log(message: string): void; export function error(message: string, code: number): void; export const DEFAULT_LEVEL: string; ``` **Remember:** Declaration files only have type signatures — no implementations. ## Global Declarations Global declarations make types available everywhere without imports: ```typescript // global.d.ts declare const MY_API_KEY: string; declare function showNotification(message: string): void; interface Window { myCustomProperty: string; } ``` **When to use:** For browser globals, environment variables, or global utilities. ## Module Declarations Declare types for JavaScript modules without type definitions: ```typescript declare module "math-utils" { export function add(a: number, b: number): number; export function subtract(a: number, b: number): number; export const PI: number; } ``` ## @types Packages Install community-maintained type definitions from DefinitelyTyped: ```bash npm install --save-dev @types/node npm install --save-dev @types/express npm install --save-dev @types/react ``` **Tip:** Prefer `@types` packages over writing custom declarations. ## Declaration Merging TypeScript merges multiple declarations of the same name: ```typescript // Both declarations merge into one module declare module "utils" { function format(value: string): string; } declare module "utils" { function parse(value: string): string; } import { format, parse } from "utils"; ``` ## Migrating JavaScript to TypeScript Write a `.d.ts` file alongside existing JS code: ```javascript // legacy.js function processUser(user) { return `${user.name} (${user.email})`; } module.exports = { processUser }; ``` ```typescript // legacy.d.ts export function processUser(user: { name: string; email: string }): string; ``` ## Best Practices - Use `@types` packages when available - Keep declarations minimal — only describe the public API - Use interfaces over types for object shapes that might be extended - Generate declarations with `tsc --declaration` for your own libraries - Test that declarations match the actual implementation ## Common Mistakes - Forgetting to declare global types causes undefined variable errors - Adding implementations to `.d.ts` files — they should only have types - Not installing `@types` packages causes implicit `any` errors - Over-declaring — only declare what the library actually exports
No changes yet
Reset to original
Submit suggestion
cancel