Declaration Files (.d.ts)
Declaration files describe the types of existing JavaScript code without containing any implementation.
What they contain
ts
// types/analytics.d.ts
declare function trackEvent(name: string, data?: object): void;
declare const VERSION: string;
declare module 'some-js-library' {
export function doSomething(value: string): number;
export interface Options {
timeout: number;
retries: number;
}
}When you need them
- Third-party JS libraries without built-in types (installed from
@types/...). - Your own JS code that you want to use in a TS project.
- Global variables injected by scripts (e.g.
window.analytics). - Ambient module declarations for non-TS files (CSS, SVG imports).
@types packages
bash
npm install -D @types/lodash
npm install -D @types/nodeThese are community-maintained declaration files from the DefinitelyTyped repository.
Augmenting existing types
ts
// extend the global Window interface
declare global {
interface Window {
analytics: Analytics;
}
}When you install a library and TypeScript says
Could not find a declaration file- you either need@types/...or to write a.d.tsyourself.
updated
did you know it?