What are declaration files in TypeScript?

In TypeScript, we use declaration files to tell TypeScript about the types in a JavaScript module. These files end with .d.ts. They describe the parts of JavaScript libraries or modules, for example, their shape and how to use them, so TypeScript knows how to interact with them.

For instance, let's say there's a JavaScript library called myLibrary that we want to use in a TypeScript application:

// myLibrary.ts
export function sayHello(name: string): string {
return `Hello, ${name}!`;
}
myLibrary.ts

The above function receives a string name and returns a string with Hello.

To use myLibrary in TypeScript, we need to define a declaration file myLibrary.d.ts:

// myLibrary.d.ts
declare module 'myLibrary' {
export function sayHello(name: string): string;
}
myLibrary.d.ts

The above file says that there's a module called myLibrary which has a function sayHello that takes a string and returns a string.

Coding example

Now, let's call the sayHello function in a TypeScript file like this:

main.ts
myLibrary.ts
myLibrary.d.ts
import { sayHello } from './myLibrary';
// TypeScript knows this is correct
let greeting = sayHello("Educative");
console.log(greeting);

Let's try to call the sayHello incorrectly:

main.ts
myLibrary.ts
myLibrary.d.ts
import { sayHello } from './myLibrary';
// This will cause a TypeScript error because sayHello
// expects a string, not a number
let wrongGreeting = sayHello(123);
console.log(wrongGreeting);

The TypeScript compiler will use the declaration file to understand the types used by myLibrary and will throw an error if we try to use sayHello incorrectly.

Conclusion

Declaration files provide a way to take advantage of TypeScript's static type checking and auto-completion for JavaScript libraries and modules, which can significantly improve development speed, quality, and safety.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved