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.tsexport function sayHello(name: string): string {return `Hello, ${name}!`;}
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.tsdeclare module 'myLibrary' {export function sayHello(name: string): string;}
The above file says that there's a module called myLibrary
which has a function sayHello
that takes a string and returns a string.
Now, let's call the sayHello
function in a TypeScript file like this:
import { sayHello } from './myLibrary';// TypeScript knows this is correctlet greeting = sayHello("Educative");console.log(greeting);
Let's try to call the sayHello
incorrectly:
import { sayHello } from './myLibrary';// This will cause a TypeScript error because sayHello// expects a string, not a numberlet 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.
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