How to generate declaration files
· Category: TypeScript
Short answer
Set declaration: true in tsconfig.json to emit .d.ts files alongside compiled JavaScript, exposing type information to consumers.
Steps
- Enable
declarationin tsconfig.json. - Run
tscto compile your project. - TypeScript generates
.d.tsfiles in theoutDirnext to the.jsfiles. - For JavaScript libraries, write
.d.tsfiles manually or usetsc --allowJs --declaration --emitDeclarationOnly. - Reference the declarations in package.json via
typesortypings.
Tips
- Use
declarationMap: trueto generate.d.ts.mapfiles for go-to-definition across packages. - Keep public APIs clean to produce readable and useful declaration files.
Common issues
- Private types leaked in public APIs cause declaration emit errors.
- Complex inferred types may generate verbose or overly generic declarations.