Declaration files for JavaScript

7.0.2

Use a .d.ts file to describe the types of JavaScript that already exists.

On this page

Match the JavaScript exports

Keep declarations next to the JavaScript they describe. The example package has a named JavaScript export, so its declaration has the same named export. Declarations describe an implementation. The JavaScript still does the work at runtime.

// index.js in an ESM package
export function formatSku(id) {
  return "SKU-" + String(id).padStart(3, "0");
}

// index.d.ts
export function formatSku(id: number): string;

Point consumers to the types

For a simple ESM package, point main at the JavaScript entry and types at its declaration. Include both when publishing. If a package uses an exports map, give the appropriate entry a types condition. Check a small consumer project with strict checking.

{
  "type": "module",
  "main": "./index.js",
  "types": "./index.d.ts",
  "files": ["index.js", "index.d.ts"]
}

Official references