AI Hints
TypeScript · Lesson 75 of 120

Declaration Files

.d.ts.

⏱ 2 min read▶ Video at 57:40🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Plain JavaScript libraries have no types. A declaration file, ending in dot D dot TS, describes them. It holds only types, no code.

Declaration Files
From the video: Declaration Files
  • JavaScript has no types
  • Describe them
  • Types only

legacy-tax.d.ts

This declaration file describes an old JavaScript module. Its function takes a price and a country code, and returns a number. There's no function body, only the shape.

legacy-tax.d.tstypescript
declare module "legacy-tax" {
  export function taxFor(price: number, country: "GB" | "FR" | "DE"): number;
}

Checked against the declaration

Now calls to the old library are checked. A wrong country code is rejected, thanks to the declaration file. Run it.

app.tstypescript
import { taxFor } from "legacy-tax";

const tax = taxFor(849.5, "US");
Output
app.ts line 3: Argument of type '"US"' is not assignable to parameter of type '"GB" | "FR" | "DE"'.
Also uses legacy-tax.d.ts
declare module "legacy-tax" {
  export function taxFor(price: number, country: "GB" | "FR" | "DE"): number;
}

Summary

Declaration files describe JavaScript code with types only. Next, the tsconfig file.

Key takeaways
  • declare module
  • Types only
  • Calls checked
Next up: tsconfig.json — the settings