Declaring modules helps TypeScript understand code from files or libraries that don't have built-in type information. It tells TypeScript what to expect so your program works smoothly.
Declaring modules in Typescript
declare module 'module-name' { // type declarations here export function example(): void; }
The declare module keyword tells TypeScript about a module without defining its code.
Inside the block, you describe the types, functions, or variables the module exports.
greet that takes a string and returns a string.declare module 'my-library' { export function greet(name: string): string; }
declare module '*.json' { const value: any; export default value; }
declare module 'cool-styles.css' { const styles: { [className: string]: string }; export default styles; }
Here, we declare a module 'greet' with a function sayHello. Then we import and use it in app.ts. This helps TypeScript know the types even if the actual module code is JavaScript or missing.
/* file: greet.d.ts */ declare module 'greet' { export function sayHello(name: string): string; } /* file: app.ts */ import { sayHello } from 'greet'; console.log(sayHello('Alice'));
Declaration files usually have the extension .d.ts.
Declaring modules does not create code; it only tells TypeScript about types.
If you have real JavaScript code for the module, make sure it matches your declarations.
Use declare module to tell TypeScript about modules without type info.
This helps avoid errors and enables type checking when using JavaScript or unknown modules.
Declaration files describe the shape of the module but do not contain actual code.