0
0
Typescriptprogramming~5 mins

Writing custom declaration files in Typescript

Choose your learning style9 modes available
Introduction

Custom declaration files help TypeScript understand code from JavaScript or third-party libraries without built-in types. They tell TypeScript what types and shapes to expect.

You use a JavaScript library without TypeScript types.
You write your own JavaScript code and want TypeScript to check it.
You want to add types for a third-party library that has no types.
You want to describe global variables or modules in your project.
You want to fix or extend existing type definitions.
Syntax
Typescript
declare module 'module-name' {
  export function functionName(param: type): returnType;
  export interface InterfaceName {
    property: type;
  }
  // other declarations
}

Use declare module to describe external modules.

Use declare global to add global variables or types.

Examples
This declares a module named 'my-lib' with a function greet that takes a string and returns a string.
Typescript
declare module 'my-lib' {
  export function greet(name: string): string;
}
This adds a new property myGlobalVar of type number to the global Window interface.
Typescript
declare global {
  interface Window {
    myGlobalVar: number;
  }
}
This declares a module with an interface and a function that uses it.
Typescript
declare module 'awesome-tool' {
  export interface Options {
    verbose: boolean;
  }
  export function run(options: Options): void;
}
Sample Program

This example shows a custom declaration file for a module 'math-utils' that exports two functions. Then the usage file imports and uses them with type safety.

Typescript
// custom.d.ts

declare module 'math-utils' {
  export function add(a: number, b: number): number;
  export function multiply(a: number, b: number): number;
}

// usage.ts
import { add, multiply } from 'math-utils';

console.log(add(2, 3));
console.log(multiply(4, 5));
OutputSuccess
Important Notes

Declaration files usually have the extension .d.ts.

They only describe types and do not contain actual code implementations.

Place custom declaration files in a folder included in your tsconfig.json or reference them explicitly.

Summary

Custom declaration files tell TypeScript about types in JavaScript or untyped libraries.

Use declare module to describe modules and declare global for global types.

They help TypeScript check your code and improve editor support.