liveBook · Manning

Declaration

As explained in Essential TypeScript 5, Third Edition

The declaration compiler option is a TypeScript setting that causes declaration files to be emitted for compiled source.

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

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains configuration, emitted filenames, inferred declarations, and allowJS limitations without detailing declaration-file design.
Examples
Uses tsconfig.json, src/index.ts, dist/index.d.ts, inferred tax variables, and exported formatter functions.
What it assumes
Assumes familiarity with TypeScript compilation, tsconfig.json, JavaScript, and inferred types; clarifies generated declarations from examples.
What you can do after
Operate/configure TypeScript to emit declaration files and diagnose inferred types through generated output.
How it connects
Connects TypeScript compilation with JavaScript output, type inference, declaration files, exported features, and allowJS.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.