Declaration Files

Declaration files (also known as .d.ts files) are used to provide type information for existing JavaScript code that doesn’t have any type annotations.

When you import a JavaScript library, TypeScript may not be able to understand the types and functions defined in the JavaScript code. This can lead to issues with type safety and make it difficult to use the imported code in a TypeScript project.

Declaration files provide a way to address this issue by defining the types and functions for the JavaScript code so that TypeScript can understand them. They essentially tell TypeScript what the shape of the code is, without information about the concrete implementation.

Example:

index.d.ts
1
2
3
4
5
6
7
8
9
export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object;

export function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;

export function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;

export function isCancel(value: any): value is Cancel;

export function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;

Declaration vs. Definition

A declaration introduces an identifier (such as a variable or a function) to the compiler, while a definition provides the implementation or value for that identifier.

Example:

1
2
3
4
5
6
7
// Here is a declaration:
type Greet = (name: string) => void;

// Here is a definition:
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}