0
0
Typescriptprogramming~5 mins

Declaring modules in Typescript

Choose your learning style9 modes available
Introduction

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.

When you use a JavaScript library without TypeScript types.
When you want to add types for a custom module you wrote in plain JavaScript.
When importing files like JSON or CSS that TypeScript doesn't know how to handle by default.
When you want to tell TypeScript about a module that exists but has no type info.
When you want to avoid errors about missing modules during compilation.
Syntax
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.

Examples
This declares a module named 'my-library' with a function greet that takes a string and returns a string.
Typescript
declare module 'my-library' {
  export function greet(name: string): string;
}
This lets you import any JSON file as a module with any content.
Typescript
declare module '*.json' {
  const value: any;
  export default value;
}
This declares a CSS module where class names map to strings, useful for importing CSS files.
Typescript
declare module 'cool-styles.css' {
  const styles: { [className: string]: string };
  export default styles;
}
Sample Program

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.

Typescript
/* file: greet.d.ts */
declare module 'greet' {
  export function sayHello(name: string): string;
}

/* file: app.ts */
import { sayHello } from 'greet';

console.log(sayHello('Alice'));
OutputSuccess
Important Notes

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.

Summary

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.