Syntax
declare module "name" { }
declare function fn(): type;Examples
Declaring Types for an Untyped Module
Adding type information for a JavaScript library that has none.
// my-library.d.ts
declare module "my-untyped-library" {
export function doSomething(value: string): number;
export const version: string;
}
// Now "my-untyped-library" can be imported with full type checking,
// even though the actual library is plain, untyped JavaScriptDeclaring Global Variables
Describing a global variable injected by an external script, like an analytics library.
// globals.d.ts
declare const analytics: {
track: (event: string, data?: object) => void;
};
// Now "analytics" can be used anywhere in the project with type checking,
// even though it is never explicitly importedBest practices
- Check DefinitelyTyped (the @types/ npm scope) first before writing your own declaration file - many popular untyped libraries already have community-maintained types
- Ship a .d.ts file alongside your own published TypeScript library so consumers get full autocomplete and type checking without needing separate type packages
- Keep hand-written declaration files minimal and focused only on what you actually use from the untyped library, rather than fully typing its entire API upfront
- Use declare global carefully and sparingly for genuinely global values (like a script-injected variable) - overuse can make type origins confusing
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook