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
| Source | How |
|---|---|
| TS libraries | Compiler emits them next to .js output. |
| JS libraries with types | Library ships its own .d.ts in node_modules/lib/index.d.ts. |
| JS libraries without types | Community types in @types/lib from DefinitelyTyped. |
| Hand-rolled augmentations | Files 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.
Four characters.
Discussion
Loading…