Migrating JavaScript to TypeScript

Migration happens in steps. "allowJs": true lets .js and .ts mix (0 errors at first), "checkJs": true or // @ts-check starts checking .js, JSDoc (@param…

A 200-file JavaScript project has to move to TypeScript. Rename every file to .ts today, and tomorrow morning you're greeted by hundreds of errors, and every other piece of work stops with them.

Luckily, migrating doesn't have to happen all at once. TypeScript can read .js and .ts files side by side, so you can move over bit by bit while the app keeps running. It's like renovating a house you still live in: one room at a time, nobody has to move out, and each finished room can be used straight away.

Step 1: allowJs, so .js and .ts can mix

This is the src/cart.js we're moving (and the one the Lab uses):

export function totalPrice(items, discount) {
  let total = 0
  for (const item of items) {
    total += item.price * item.quantity
  }
  return total - total * discount
}

const shopping = [
  { name: "Book", price: 25, quantity: 2 },
  { name: "Pencil", price: 3, quantity: 5 },
]

const label = document.querySelector("#total")
label.textContent = totalPrice(shopping, "10%")

There's a bug on the last line: the discount is written "10%", text, not the number 0.1. In the browser, the label shows NaN. Let's see at which step TypeScript catches it.

With no settings at all, tsc ignores .js files. If src only holds .js files, it even says No inputs were found in config file ... ts(18003). So the starting tsconfig is:

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": false,
    "strict": false,
    "target": "es2022",
    "module": "esnext",
    "noEmit": true
  },
  "include": ["src"]
}

Step 2: checkJs, start checking the .js

Switch to "checkJs": true. Now .js files get checked too, and 1 error appears on the last line: Type 'number' is not assignable to type 'string'. ts(2322). totalPrice returns a number, while textContent needs text.

Want to check just one file? Put // @ts-check on the first line of that file, without checkJs. The other way round, // @ts-nocheck turns checking off for one file.

The "10%" bug isn't caught yet. TypeScript doesn't know discount must be a number, because the parameter has no type yet.

Step 3: JSDoc, types inside comments

Before renaming the file, you can add types through JSDoc comments. The code stays plain JavaScript:

/** @typedef {{ name: string, price: number, quantity: number }} Item */

/**
 * @param {Item[]} items
 * @param {number} discount
 * @returns {number}
 */
export function totalPrice(items, discount) {

Now there are 2 errors: the one from before, plus Argument of type 'string' is not assignable to parameter of type 'number'. ts(2345) on "10%". The bug is caught.

Step 4: turn strict on one check at a time

Then tighten the checking, one setting at a time. In this file, "noImplicitAny": true still gives 2 errors (every parameter has a type already), and "strictNullChecks": true makes it 3: 'label' is possibly 'null'. ts(18047), because querySelector returns null when the element isn't there. Finally, replace them all with "strict": true.

Why not strict from the start? In this small file alone, checkJs with "strict": true and no JSDoc gives 4 errors straight away, not 1: two parameters with no type (ts(7006)), a label that may be null, and a number put into text. A project with 200 files can get hundreds of errors at once, and the migration stalls. One setting, fix its errors, commit, then move on to the next setting.

Step 5: rename to .ts

The file becomes cart.ts, and the JSDoc is replaced with TypeScript types:

interface Item {
  name: string
  price: number
  quantity: number
}

export function totalPrice(items: Item[], discount: number): number {

Still the same 3 errors. Careful: if you only rename the file and leave the JSDoc as it is, TypeScript does not use JSDoc types in a .ts file. items and discount become untyped any, and you get Parameter 'items' implicitly has an 'any' type. ts(7006). JSDoc only provides types in .js files.

Last, fix the bug:

const label = document.querySelector("#total")
if (label) {
  label.textContent = String(totalPrice(shopping, 0.1))
}

0 errors, and the label shows 58.5.

Step Errors
1. allowJs 0
2. checkJs 1
3. JSDoc 2
4. strict 3
5. .ts 3
6. fixed 0

⚠️ Steps that get skipped or done backwards

TL;DR: Migration happens in steps. "allowJs": true lets .js and .ts mix (0 errors at first), "checkJs": true or // @ts-check starts checking .js, JSDoc (@param {number} discount) adds types without renaming the file, then the strict settings are turned on one at a time until "strict": true, because strict from the start can bring hundreds of errors at once. When a file becomes .ts, write its types in TypeScript syntax, because JSDoc isn't used in .ts files. Remember too that since TypeScript 6.0 strict is on when it isn't written.

⚡ .js and .ts can mix

Write:

"allowJs": true,
"checkJs": false,
"strict": false

Meaning: allowJs lets .js files join a TypeScript project, so you can move over bit by bit while the app keeps running. You start at 0 errors. "strict": false must be written, because since TypeScript 6.0 strict is on when nothing is written.

⚡ Types through JSDoc

Write:

/**
 * @param {Item[]} items
 * @param {number} discount
 * @returns {number}
 */
export function totalPrice(items, discount) {

Meaning: "checkJs": true starts checking .js files. JSDoc comments give types without renaming the file, and the "10%" discount bug that slipped through before is now caught.

⚡ Turn strict on one check at a time

Guess first: why not switch on "strict": true from the start?

Even in one small file it gives 4 errors at once, not 1. A 200-file project can have hundreds of errors in one go, and the migration stalls.

Meaning: Switch on one setting, like noImplicitAny, fix its errors, commit, then move to the next, until you reach "strict": true. When a file is renamed to .ts, move its types into TypeScript syntax, because JSDoc isn't used for types in .ts files.

What you will learn