TypeScript declaration files, commonly known as "typings" or ".d.ts" files, are used to provide type information for JavaScript code. They allow you to use TypeScript with existing JavaScript libraries or modules that don't have native TypeScript support. Here's a step-by-step guide on how to create and use TypeScript declaration files:
Create a file with a ".d.ts" extension, for example, myLibrary.d.ts
. Inside this file, declare the types for the library:
typescript// myLibrary.d.ts
declare module 'my-library' {
export function myFunction(arg: string): number;
export const myVariable: string;
}
tsc
with --declaration
flagIf you have the original JavaScript file and want TypeScript to generate the declaration file for you, you can use the TypeScript Compiler (tsc) with the --declaration
flag:
bashtsc --declaration myLibrary.js
This will generate a myLibrary.d.ts
file with inferred types.
Once you have the declaration file, you can use it in your TypeScript code:
typescript// main.ts
import { myFunction, myVariable } from 'my-library';
const result: number = myFunction(myVariable);
console.log(result);
Ensure that the TypeScript compiler recognizes the declaration file. You can do this by adding a reference comment at the top of your TypeScript file:
typescript/// <reference types="my-library" />
import { myFunction, myVariable } from 'my-library';
const result: number = myFunction(myVariable);
console.log(result);
If you're using an external library with pre-existing declaration files, you can install them using a package manager like npm:
bashnpm install @types/library-name
Replace "library-name" with the actual name of the library. The @types/
scope is a convention for TypeScript declaration packages.
In your declaration file, you might need to use "ambient declarations" when you're not providing an actual implementation. For example:
typescript// myLibrary.d.ts
declare module 'my-library' {
export function myFunction(arg: string): number;
export const myVariable: string;
export default something; // Ambient declaration for an exported entity with no implementation
}
This allows you to declare types without providing actual code.
Always check if the library you're working with already has existing TypeScript declaration files. Many popular libraries have dedicated @types
packages that you can directly install.
Remember to refer to the TypeScript documentation for the most up-to-date information: TypeScript Declaration Files.