patterntypescriptnoneModerate
Declaration Files (.d.ts): Typing Untyped JavaScript Modules
Viewed 0 times
TypeScript 1.0+
declaration filed.tsambient moduleuntyped librarydeclare module
Error Messages
Problem
A JavaScript library has no TypeScript types and no @types/ package. Importing it gives 'Could not find a declaration file for module' and TypeScript treats all its exports as 'any'.
Solution
Create a local .d.ts file to describe the module's public API.
// src/types/some-untyped-lib.d.ts
declare module 'some-untyped-lib' {
export interface Options {
timeout?: number;
retries?: number;
}
export function connect(url: string, options?: Options): Connection;
export interface Connection {
query(sql: string): Promise<unknown[]>;
close(): void;
}
export default connect;
}
// For libraries that export a single function:
declare module 'legacy-lib' {
function legacyFn(input: string): string;
export = legacyFn;
}Why
TypeScript's module resolution checks for .d.ts files alongside JavaScript files or in @types/. A hand-written declaration file provides type information without modifying the original source.
Gotchas
- The declaration file must be included in the TypeScript compilation (via tsconfig 'include' or 'typeRoots').
- A 'declare module' with a wildcard ('*.svg') can type all imports of a pattern.
- Use 'skipLibCheck: true' if third-party .d.ts files have errors you cannot control.
Revisions (0)
No revisions yet.