Declaration Files for JavaScript Libraries
What you'll learn: How to automatically generate .d.ts declaration files from your existing JavaScript code using TypeScript's compiler options.
The Automatic Declaration Generation Pattern
You've already learned how to write declaration files by hand. But what if you're gradually migrating a JavaScript library to TypeScript? There's a powerful workflow: keep your source code in JavaScript (for now), but let TypeScript generate type definitions automatically.
This is where allowJs and declaration work together as a team.
How allowJs and declaration Combine
The allowJs compiler option tells TypeScript to process .js files, not just .ts files. When you pair it with the declaration flag, TypeScript does something clever: it analyzes your JavaScript code, infers types from usage patterns, and generates corresponding .d.ts files.
In your tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "./dist"
},
"include": ["src/**/*.js"]
}
This configuration says: "Accept JavaScript files, generate declaration files, and skip emitting the JavaScript itself (since you already have it)."
What Gets Generated
TypeScript infers types from your JavaScript's structure. For a file like utils.js:
export function greet(name) {
return `Hello, ${name}!`;
}
export const MAX_COUNT = 100;
Running tsc generates utils.d.ts:
export function greet(name: any): string;
export const MAX_COUNT: 100;
Notice that TypeScript inferred the return type (string) and the literal value (100), but couldn't determine the parameter type (falls back to any).
Improving Inference with JSDoc
You can enhance the generated declarations using JSDoc comments in your JavaScript:
/**
* @param {string} name
* @returns {string}
*/
export function greet(name) {
return `Hello, ${name}!`;
}
Now the generated .d.ts will have name: string instead of name: any.
When This Approach Shines
This technique is ideal for:
- Publishing JavaScript libraries with types without rewriting in TypeScript
- Incremental migration where you generate types first, verify them, then convert later
- Monorepos where some packages remain JavaScript but need type definitions for TypeScript consumers
Key Takeaway: Combining allowJs with declaration lets TypeScript automatically generate .d.ts files from JavaScript source code, providing type safety for consumers without requiring full migration to TypeScript.