๐ŸŽ“ A1Learner
๐Ÿ”
0 of 42 lessons completed

TypeScript Declaration Files

A declaration file describes the types of JavaScript code without holding its implementation. Libraries ship the declaration file beside the JavaScript file so typed callers get full checking.

A legacy.d.ts file

The declaration file promises a greet function and a version string. It holds no code that runs.

export declare function greet(name: string): string;
export declare const version: string;

The legacy.js file

The JavaScript file holds the real implementation and states no types. Its shapes match the promises in the declaration file.

export function greet(name = "friend") {
  return "Hello, " + name + "!";
}

export const version = "1.0.0";

Importing the declared API

The caller imports the pair by their shared base name. The output comes from the JavaScript file, and the types come from the declaration file.

import { greet, version } from './legacy';

console.log(greet('Ada'));
console.log(version);

A wrong argument is refused

The implementation would accept any value at runtime, but the declared signature requires a string. The checker refuses the number before the program runs.

import { greet } from './legacy';

console.log(greet(42));

Example

import { greet, version } from './legacy';

const guests: string[] = ['Ada', 'Grace'];

for (const guest of guests) {
  console.log(greet(guest));
}
console.log('Version: ' + version);

Key points

  • A declaration file ends in .d.ts and holds declarations only, with no function bodies.
  • The declare keyword states that the value exists somewhere else, in the JavaScript file.
  • The checker enforces the declared types on every caller, even though the implementation is plain JavaScript.
  • A call that breaks the declared types fails the compile before the program runs.

In this example, the code greets each guest through the declared function and prints the declared version string, all typed by the declaration file.

Note

The pair works because the two files share a base name, so an import of that name finds both halves.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does a .d.ts file hold?