Skip to the workspace
Pebellslearn by building
Introduction to TypeScript  ›  Capstone Project

Mixing TypeScript and JavaScript

TS and JS Interoperability 12 minTypeScript and JavaScript files can live in the same project, and declaration files describe the types of JavaScript code that has none.

typescript / Mixing TypeScript and JavaScript

Explore each scene at your own pace.

01 · The rule

The rule

Mixing TypeScript and JavaScript

TypeScript and JavaScript files can live in the same project, and declaration files describe the types of JavaScript code that has none.

Plan a gradual migration using JavaScript checking, declaration files and typed modules.

Few teams start with TypeScript on day one. Usually there is already a JavaScript codebase, plus libraries written in JavaScript. The good news is that you never have to convert everything at once. TypeScript was designed to live alongside JavaScript.

The rule

JavaScript and TypeScript share a project; declaration files carry the types.

Four tools make this work.

allowJs — a compiler option that lets .js files be part of a TypeScript project. A .ts file can import from a .js file and vice versa, so you can convert one file at a time.

checkJs or // @ts-check — asks TypeScript to check JavaScript files too. checkJs turns it on for all of them; a // @ts-check comment at the top turns it on for a single file. In JavaScript you can add types through JSDoc comments:

// @ts-check

/** @param {{ id: number, title: string }} task */
function formatTask(task) {
  return task.id + ". " + task.title;
}

formatTask({ id: 1 }); // error: property 'title' is missing

Declaration files (.d.ts) — files that contain only types, no code. They describe the shape of JavaScript code so TypeScript can check your use of it:

// legacy-store.d.ts
export function loadTasks(): { id: number; title: string; done: boolean }[];

@types packages — declaration files for popular JavaScript libraries, published separately. If a library ships without types, npm install --save-dev @types/<library> often provides them. Many modern libraries include their own .d.ts files, so nothing extra is needed.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.