4 min read
•Question 32 of 48mediumWhat are Declaration Files (.d.ts)?
Type definitions for JavaScript.
What You'll Learn
- What .d.ts files are
- When you need them
- How to create them
What are Declaration Files?
Declaration files (.d.ts) contain type information without implementation. They describe the shape of JavaScript code.
code.tsTypeScript
// math.d.ts
declare function add(a: number, b: number): number;
declare function subtract(a: number, b: number): number;
declare const PI: number;Why Use Them?
- Add types to JavaScript libraries
- Share types without implementation
- @types packages use them
Finding Type Definitions
$ terminalBash
# Install types for lodash
npm install --save-dev @types/lodash
# Many packages include their own types
npm install axios # types includedCreating Declaration Files
code.tsTypeScript
// For a module
declare module "my-library" {
export function doSomething(value: string): number;
export interface Config {
debug: boolean;
}
}
// For global variables
declare global {
interface Window {
myGlobal: string;
}
}Generate from TypeScript
data.jsonJSON
// tsconfig.json
{
"compilerOptions": {
"declaration": true,
"declarationDir": "./types"
}
}