Declaration Files (.d.ts)
Declaration Files (.d.ts)
Declaration files (.d.ts) describe the types of existing JavaScript code without containing any runtime logic. They are the mechanism through which third-party libraries expose TypeScript types.
When you install a package like lodash, TypeScript looks for types in two places: types bundled with the package itself (package.json "types" field), or a corresponding @types/ package from DefinitelyTyped (e.g., @types/lodash).
// Example: manually declaring a module without types
// global.d.ts
declare module "some-untyped-library" {
export function parse(input: string): unknown;
export const version: string;
}
// Augmenting existing global types
declare global {
interface Window {
gtag: (command: string, ...args: unknown[]) => void;
}
}
export {}; // Make this file a moduleYou can generate declaration files from your own TypeScript source by setting "declaration": true and optionally "declarationMap": true in tsconfig.json. This is essential when publishing a library.
// tsconfig.json additions for library authors:
// "declaration": true, — emit .d.ts files
// "declarationDir": "types", — where to put them
// "declarationMap": true — source maps for .d.tsIf a package has no types at all, create a *.d.ts file that declares the module as any as a stopgap: declare module "mystery-lib";. Then file an issue or submit types to DefinitelyTyped.