The declaration compiler option makes TypeScript emit declaration files alongside compiled JavaScript. These files preserve inferred type information and describe exported features for other TypeScript projects while keeping the output usable as regular JavaScript. section 7.2.2 section 15.4
Listing 7.14 Configuring the compiler in the tsconfig.json file in the types folder
{
"compilerOptions": {
"target": "ES2022",
"outDir": "./dist",
"rootDir": "./src",
"declaration": true
}
}
Enable declaration generation in tsconfig.json alongside target, rootDir, and outDir settings. section 7.2.2
Inspecting inferred types
With declaration set to true, compiling src/index.ts creates dist/index.d.ts. For code containing calculateTax, price, taxAmount, and halfShare, the generated file can contain declarations such as `declare function calculateTax(amount: number): string;`, `declare let taxAmount: string;`, and `declare let halfShare: number;`. This can expose why `taxAmount / 2` produces an arithmetic-type error after calculateTax returns a string. section 7.2.2
declare function calculateTax(amount: number): string; declare let price: number; declare let taxAmount: string; declare let halfShare: number;
Inspect a generated declaration file showing inferred types for functions and variables. section 7.2.2
Declaration files are generated reliably only when the project is TypeScript-based. Enabling allowJS prevents their generation, so JavaScript dependencies must be replaced or the configuration adjusted; restart the compiler after changing the setting. section 15.4
