TypeScript Declaration Files (.d.ts)
Declaration Files (.d.ts)
Section titled “Declaration Files (.d.ts)”What are Declaration Files?
Section titled “What are Declaration Files?”Declaration files (.d.ts) describe the shape of existing JavaScript code to TypeScript. They contain only type information — no implementation.
Global Declarations
Section titled “Global Declarations”declare const API_VERSION: string;declare function fetchData(url: string): Promise<unknown>;
interface Window { __APP_CONFIG__: { apiUrl: string; debug: boolean };}Module Declarations
Section titled “Module Declarations”declare module "my-library" { export function doSomething(input: string): number; export interface Options { timeout: number; retries: number; }}Augmenting Existing Modules
Section titled “Augmenting Existing Modules”// Add types to existing modulesimport "express";
declare module "express" { interface Request { user?: { id: string; role: string }; }}Generate Declaration Files
Section titled “Generate Declaration Files”{ "compilerOptions": { "declaration": true, "declarationDir": "./types", "emitDeclarationOnly": true }}Interview Questions
Section titled “Interview Questions”Easy: What is a .d.ts file?
Medium: How do you create module declarations for a JavaScript library?
Hard: How do you augment an existing module’s types?