The compiler and runtime

Use declaration files

Understand how .d.ts files describe JavaScript APIs and where library types come from.

A declaration file contains type information without runtime implementation.

For example, a JavaScript package might export slugify(). A declaration can describe it:

declare function slugify(value: string): string
export { slugify }

The .d.ts file tells TypeScript how callers may use the JavaScript. It does not provide the function at runtime.

Many packages ship their own declarations. Inspect the package metadata or editor types before installing anything else.

For older JavaScript libraries, a matching package under @types may provide community-maintained declarations:

npm install --save-dev @types/express

Do not install @types packages automatically when the library already includes types.

If a declaration disagrees with the real JavaScript, the checker can approve code that fails at runtime. Treat declarations as contracts that must match the implementation.

Exercise: write a declaration claiming a function returns number, then make the JavaScript return a string. Notice which side TypeScript trusts.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →