iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Declaration Files (.d.ts)

A .d.ts file describes types without supplying implementation. They let TypeScript understand plain JavaScript libraries.

Where they come from

SourceHow
TS librariesCompiler emits them next to .js output.
JS libraries with typesLibrary ships its own .d.ts in node_modules/lib/index.d.ts.
JS libraries without typesCommunity types in @types/lib from DefinitelyTyped.
Hand-rolled augmentationsFiles in your own types/ folder.

What goes inside

TS — math.d.ts
export const PI: number;
export function area(radius: number): number;
export type Point = { x: number; y: number };
export default class Vec2 {
    constructor(x: number, y: number);
    x: number;
    y: number;
}

Augmenting a third-party module

TS — typings.d.ts
import 'express';

declare module 'express' {
    interface Request {
        user?: { id: number; name: string };
    }
}

Now req.user is typed across every middleware that imports the augmented Express.

Ambient module declaration

For libraries with no types and no @types package:

TS — globals.d.ts
declare module 'legacy-lib' {
    export function greet(name: string): string;
    const VERSION: string;
    export default VERSION;
}

Global declarations

TS
// Add a global to Window
declare global {
    interface Window {
        myAppVersion: string;
    }
}
export {};   // makes the file a module so `declare global` works

Asset modules

TS
declare module '*.svg'  { const src: string; export default src; }
declare module '*.css'  { const css: string; export default css; }
declare module '*.json' { const data: any;    export default data; }
Tip: Most popular libraries either ship their own types or have @types/x on npm. If both exist, the library's own types win.

Example

Example
// types.d.ts
// declare module 'legacy-lib' {
//   export function greet(name: string): string;
// }
//
// Declaration files describe shapes JS code doesn't expose itself.
// They live in node_modules/@types/* or alongside source as *.d.ts.
console.log('TS uses .d.ts to type pure-JS libraries');
Try it Yourself »

Exercise

TypeScript declaration files use this extension.

types.

Test yourself

Q1. .d.ts files contain…
Q2. Community types live in…
Q3. Augment a third-party module via…

Discussion

Loading…