// types/env.d.ts
declare global {
interface Window {
analytics?: { track(event: string): void };
}
}
declare module "some-lib" {
interface Options {
retries?: number;
}
}
export {};
A .d.ts file holds only type declarations, no runtime code. declare tells TypeScript that something exists at runtime, without giving its code. To add properties, use declare module for a library and declare global for window.
A .d.ts file describes JavaScript that exists somewhere else. For example:
- a library without built-in types (types often come from
@typespackages) - globals that a script adds to the page
- non-code imports, such as CSS modules
Example of declare: declare const API_URL: string says that API_URL exists, without defining it.
To extend existing types, you rely on interface declaration merging: two interfaces with the same name combine into one.
- Module augmentation uses
declare module "some-lib"inside a file that is itself a module. It adds members to an interface that the library exports. - For globals such as
Window, usedeclare globalin a module file.
The export {} line makes the file a module. Both forms need this.
Finally, the tsconfig must include the file.
- A
.d.tsfile holds types only and describes JavaScript that exists somewhere else. declaresays something exists at runtime without giving its code.declare moduleadds members to a library's exported interfaces.declare globalextends globals likeWindow.- Augmentation relies on interface merging and must be in a module file, for example with
export {}.
Read more