Migrating a JavaScript codebase to TypeScript

Intermediate · 19 min

Move a JavaScript project to TypeScript gradually with allowJs, checkJs, JSDoc types, and strictness you tighten one file or one flag at a time.

Before thisStrict mode and the compiler flags that matterDeclaration files and DefinitelyTyped

Ambient Coder · 19 min

Migrating a JavaScript codebase to TypeScript

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ambient CoderReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A migration should never stop the product shipping. The goal is a codebase that builds and runs at every step, with JavaScript and TypeScript files living side by side until the last one is converted.
  • `allowJs` lets the compiler include `.js` files in the project, so TypeScript files can import them. `checkJs` goes further and type-checks those JavaScript files too, and `// @ts-check` at the top of one file opts in just that file.
  • JSDoc comments such as `@param`, `@returns`, and `@typedef` give JavaScript files real types the checker enforces, which lets you add types before you rename a single file.
  • Strictness can be tightened along two axes: file by file, converting and fixing leaf modules first, and flag by flag, enabling `noImplicitAny` then `strictNullChecks` and the rest of `strict` once each wave of errors is fixed.
  • Untyped dependencies are handled with `@types` packages where they exist and a short `declare module` shim where they don't, so third-party code never blocks your own conversion.

Why not convert everything at once

Picture a 400-file JavaScript app. You rename every .js to .ts, turn on strict, and run tsc. Five thousand errors. Fixing them takes weeks, and meanwhile every other branch in the repo conflicts with yours. Most big-bang migrations die right there.

TypeScript was designed to avoid this. It can read JavaScript, check JavaScript, and mix the two in one project. That lets you migrate the way you would replace the wiring in a house people still live in: one room at a time, with the lights working every evening.

Step 1: let both languages share a project

Start with a tsconfig that accepts the code as it is today:

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": false,
    "strict": false,
    "target": "es2022",
    "module": "nodenext",
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": ["src"]
}

allowJs puts .js files into the program. A new billing.ts can import the old users.js, and tsc copies the JavaScript through to outDir alongside the compiled TypeScript. Set strict: false explicitly, since recent TypeScript versions default it to on. If a bundler or framework already builds your code, keep it doing that and add noEmit: true. TypeScript then just checks.

At this point nothing is safer yet, but nothing is broken either. Commit it.

Step 2: type-check JavaScript before renaming it

The compiler can check plain JavaScript files. Add // @ts-check to the top of one file and the checker reads it with inference, as if it were TypeScript with no annotations. Where inference isn’t enough, JSDoc comments act as annotations:

// @ts-check

/**
 * @typedef {object} User
 * @property {string} id
 * @property {string} [email]
 */

/**
 * @param {User[]} users
 * @param {string} id
 * @returns {User | undefined}
 */
export function findUser(users, id) {
  return users.find((u) => u.id === id);
}

const user = findUser([{ id: "1" }], "1");
user.email.toLowerCase();
// with strictNullChecks on: 'user' is possibly 'undefined'.

This is still a .js file. Node runs it unchanged and no build step touches it. But the checker now knows what a User is and catches the unhandled undefined. Once most files carry // @ts-check, flip checkJs: true in the config and use // @ts-nocheck on the few files that aren’t ready.

Some projects stop here on purpose. Libraries such as Svelte keep their source in JavaScript with JSDoc types and still ship full type definitions. For a migration, though, JSDoc is usually a stepping stone: the types you write in comments translate almost one to one into annotations when you rename.

Step 3: rename, starting from the leaves

Convert files in dependency order, starting with leaf modules: utilities, constants, data models, anything that imports nothing else from your own code. A leaf can be typed completely in isolation, and every file that imports it immediately benefits. Working from the top down instead means typing callers against modules that are still any, and doing it twice.

Renaming users.js to users.ts usually surfaces three kinds of error:

  • Implicit any parameters. Annotate them.
  • Objects built up property by property (const cfg = {}; cfg.port = 3000;). Declare the shape up front or build the object in one literal.
  • Imports of packages that ship no types. Install the @types/ package if one exists. If not, a one-line shim in a .d.ts file, declare module "legacy-lib";, makes the import type as any until someone writes real declarations. Declaration files and DefinitelyTyped covers both.

When one line can’t be fixed today, // @ts-expect-error with a short reason is better than an any. It is searchable, and it fails loudly once the underlying problem is fixed.

Step 4: tighten strictness flag by flag

With most files converted under strict: false, turn the screws one flag at a time. A sensible order:

  1. noImplicitAny. Until every value has a real type, the other checks have little to work with.
  2. strictNullChecks. Usually the largest wave of errors, and the one that finds the most real bugs.
  3. The remaining members of the strict family, then strict: true itself.
  4. Extras such as noUncheckedIndexedAccess, as covered in strict mode and the compiler flags that matter.

If one flag produces too many errors to fix in a single change, apply it to part of the codebase first. A second config, say tsconfig.strict.json, that extends the main one, sets the new flag, and includes only the folders already cleaned up can run in CI. The folder list grows until it covers everything, and then the flag moves into the main config.

What the video covers

Ambient Coder migrates a small Node.js app gradually: setting up a tsconfig, running in the hybrid allowJs mode, fixing errors one file at a time, declaring module types for packages without them, and finally migrating the tests. That is Steps 1 and 3 of this lesson in action. The video is from 2021 and uses CommonJS with esModuleInterop, so expect its module settings to differ from the nodenext config above. It also skips checking JavaScript in place, which is why Step 2 is covered in full here. Josh Goldberg’s talk in the links tells the team-level story of a real migration at Codecademy.

Check yourself

  1. 01What is the difference between `allowJs` and `checkJs`?

    `allowJs` lets `.js` files be part of the program, so TypeScript code can import them and `tsc` can emit them, but it doesn't report type errors inside them. `checkJs` type-checks those JavaScript files as well, using inference and any JSDoc annotations they contain.

  2. 02How can you get type checking in one JavaScript file without turning on `checkJs` for the whole project?

    Put `// @ts-check` as the first line of that file. It opts the single file into checking. The reverse, `// @ts-nocheck`, opts a file out when `checkJs` is on.

  3. 03Why convert leaf modules, the ones that import nothing else from your code, before the modules that depend on them?

    A leaf module's types depend only on itself, so it can be typed completely. Once it is, every file that imports it gets real types for free, and converting those files later turns up real mismatches instead of a pile of `any`.

  4. 04Your migrated project has `strict: false`. Why turn on `noImplicitAny` before `strictNullChecks`?

    `noImplicitAny` forces every parameter and value to have a real type. Until that is done, many values are silently `any`, and null checks on an `any` find nothing. Typing everything first makes the `strictNullChecks` errors that follow accurate and meaningful.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark