TypeScript Reference ยท Modules and Declaration Files
Writing a TypeScript .d.ts file
A worked guide to typing a JavaScript library with a .d.ts file: exports, overloads, callbacks, classes, options objects, and checking the declaration.
A declaration file describes the shape of JavaScript code so that TypeScript can check calls to it. This page walks through typing a small imaginary library, step by step. The method is always the same: look at how the library is used (exports, call shapes, options, callbacks), then write signatures that accept the valid calls and reject the invalid ones.
Suppose the library tinybus is plain JavaScript: it exports a function createBus() that returns an object with on, off and emit, plus a numeric constant VERSION. Its .d.ts file would be tinybus.d.ts (or index.d.ts) next to the JavaScript.
// index.d.ts export const VERSION: string; export interface Bus<Events extends Record<string, unknown[]>> { on<K extends keyof Events>(name: K, handler: (...args: Events[K]) => void): () => void; emit<K extends keyof Events>(name: K, ...args: Events[K]): void; } export function createBus<Events extends Record<string, unknown[]>>(): Bus<Events>;
Try it
A single runnable file cannot be a .d.ts, so this example does the next best thing: it writes the declaration as types and implements it, which proves that the declaration and the code agree.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
The run stops with the real compiler errors. The first bad call is reported as Expected 3 arguments, but got 2 (line 8, because "move" needs two numbers) and the unknown event name as Argument of type '"logout"' is not assignable to parameter of type '"login" | "move"' (line 9).
The method
- Pick the module shape. For an ES module or CommonJS module with named exports, write
exportdeclarations. For CommonJS code that setsmodule.exports = fn, writeexport = fn;(and useesModuleInteropto import it). For a script that creates a global, writedeclareglobals or adeclare namespaceand, for a UMD library,export as namespace Name;. - Type the values, not the implementation. Use
export function name(...): T;,export const x: T;, andexport class C { ... }with member signatures only. There are no bodies and no initializers. - Model options objects with interfaces and make optional options optional (
retries?: number). Preferreadonlyfor fields the library never changes. - Use overloads when the return type depends on the arguments, listing the most specific signature first. Use generics when the result relates to the input type.
- Type callbacks precisely, including the
thisparameter if the library calls handlers with a specificthis, andvoidfor return values the library ignores. - Prefer
unknowntoanywhere the library accepts anything, so callers must narrow before use. - Add JSDoc comments to declarations; editors show them on hover.
- Test the declaration with a small
.tsfile of valid calls and// @ts-expect-errorlines for calls that must fail. Tools such astsdorexpect-typeautomate this.
Usage notes
- Do not use
Function,Objector{}as parameter types. Write the call signature ((a: string) => void) orRecord<string, unknown>. - Return types matter more than parameters. A wrong
anyreturn disables checking for every caller. - Order overloads from most to least specific; the first matching signature wins.
- Do not declare optional things as overloads when an optional parameter would do.
- Keep the
.d.tsnext to the JS and pointpackage.jsontypesat it (see @types packages); or generate it from typed sources (Generating declarations). - Quick start:
declare module "tinybus";makes everythinganywhile you work out the real types (declare).