"declaration"
Generates .d.ts files with types next to the compiled JavaScript.
Example
#{
"compilerOptions": {
"declaration": true,
"outDir": "./dist"
},
"include": ["src"]
}Definition and usage
#With declaration: true, the compiler writes a .d.ts file next to every .js file. It contains only types: function signatures, interfaces, and the types of classes and constants, with no implementation.
This is essential when publishing a library to npm. The user gets working JavaScript and the types that let the editor offer suggestions and check calls. The path to the declarations is given in package.json with the types field, or the types condition in the exports field.
Related options: declarationDir writes declarations to a separate folder, emitDeclarationOnly generates only .d.ts files (when another tool builds the JavaScript), and declarationMap lets you jump in the editor from a type straight to the .ts source file.
Syntax
#"declaration": trueMore examples
#// src/progress.ts
export interface Progress {
done: number
total: number
}
export function percent(progress: Progress): number {
return Math.round((progress.done / progress.total) * 100)
}
// dist/progress.d.ts (generated):
// export interface Progress {
// done: number;
// total: number;
// }
// export declare function percent(progress: Progress): number;{
"name": "@codeworlds/progress",
"type": "module",
"exports": {
".": {
"types": "./dist/progress.d.ts",
"default": "./dist/progress.js"
}
}
}Good practices
#- Applications, e.g. on Next.js or Vite, don’t need declarations. Enable
declarationin libraries and in packages shared across a monorepo. - Write out the return types of exported functions explicitly. The declarations are then easier to read, and the
isolatedDeclarationsoption (TypeScript 5.5) actually requires it, so that other tools can generate.d.tswithout full type checking.
Related entries
#- declare and .d.ts filesDescribing the types of something that exists outside your TypeScript code: global variables, JavaScript libraries, and modules.
- "outDir" and "rootDir"The folder where compiled code goes, and the folder of the sources.
- "sourceMap"Generates .js.map source maps, so the debugger shows your TypeScript code instead of the generated JavaScript.
- "skipLibCheck"Skips error checking in .d.ts declaration files, which speeds up compilation.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.