Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 96 ยท Modules and Declarations

Migrating JavaScript to TypeScript

Move a JavaScript codebase to TypeScript gradually - allowJs, checkJs, JSDoc types, @ts-check, @ts-expect-error vs @ts-ignore, stricter checks and a plan.

Most TypeScript code is not written from scratch. It starts life as a JavaScript project that grew large enough for someone to say "we need types." The good news is that you never have to stop the world and rewrite everything. TypeScript was designed so that JavaScript and TypeScript files can live in the same project, so you can convert one file, one folder or one feature at a time while the app keeps shipping.

This lesson walks through the tools that make a gradual migration work: letting the compiler read JavaScript (allowJs), type-checking JavaScript you haven't renamed yet (checkJs, // @ts-check and JSDoc types), the errors you'll hit when a file becomes .ts, the two suppression comments and why one is much better than the other, and how to turn strictness up in steps. It ends with a migration plan you can follow on a real project.

Step one: let TypeScript see your JavaScript

A TypeScript project normally only compiles .ts files. The allowJs option tells the compiler to include .js files too. They are not type-checked yet, but TypeScript reads them: it infers types from their code, so a new .ts file can import an old .js module and get useful autocomplete straight away.

JSON
{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": false,
    "strict": false,
    "noEmit": true,
    "module": "nodenext",
    "target": "es2024"
  },
  "include": ["src"]
}

Use noEmit if another tool (Vite, esbuild, Next.js, Node's type stripping) already turns your code into JavaScript and you only want tsc as a checker. Run npx tsc and you'll usually see zero errors with this config. That's the point: you have a working baseline before you change anything. (The tsconfig lesson covers the options in detail.)

Step two: check JavaScript files with JSDoc

You can get real type checking without renaming a single file. Add // @ts-check at the top of a .js file (or set "checkJs": true for all of them), and TypeScript checks it like TypeScript, reading types from JSDoc comments:

JavaScript
// @ts-check

/**
 * @typedef {object} CartItem
 * @property {string} sku
 * @property {number} price  Price in cents.
 * @property {number} [quantity]  Defaults to 1.
 */

/**
 * @param {CartItem[]} items
 * @returns {number}
 */
export function cartTotal(items) {
  return items.reduce((sum, item) => sum + item.price * (item.quantity ?? 1), 0);
}

/** @type {CartItem[]} */
const items = [{ sku: 'A1', price: 499 }, { sku: 'B2', price: '250' }];

console.log(cartTotal(items).toFixed(2));
cartTotal('A1');

Running the TypeScript 7 compiler with --allowJs --checkJs on this file reports:

TEXT
cart.js(19,56): error TS2322: Type 'string' is not assignable to type 'number'.
cart.js(22,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'CartItem[]'.

Those are the same checks and error codes you get in .ts files. The common JSDoc tags map directly onto TypeScript syntax:

JSDoc TypeScript equivalent
/** @type {string[]} */ const tags = []; const tags: string[] = [];
@param {number} [count] count?: number
@returns {Promise<User>} : Promise<User>
@typedef {object} User + @property lines interface User { ... }
@typedef {'idle' | 'busy'} Status type Status = 'idle' | 'busy';
@template T <T> on a function
/** @import { User } from './types.js' */ (TS 5.5+) import type { User } from './types.js';
/** @satisfies {Config} */ satisfies Config

JSDoc types are a complete migration path on their own. Some well-known libraries stay in JavaScript forever and ship types generated from JSDoc (tsc --declaration --allowJs --emitDeclarationOnly). For an application, though, .ts files are shorter and clearer, so JSDoc is usually a stepping stone: check a file first, fix what it finds, then rename it.

Our editor compiles a single main.ts file, so the JSDoc examples on this page are read-only. Every runnable example below is TypeScript, showing what happens after you rename a file.

Step three: rename a file and read the errors

Renaming cart.js to cart.ts switches the file to full TypeScript rules. If your project already has strict on, the first thing you'll meet is implicit any: JavaScript parameters have no types, and strict mode refuses to guess. This example is pasted straight from a JavaScript file and fails on purpose:

TypeScript JavaScript code under strict TypeScript (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is only the error list, because a type error stops the run:

TEXT
main.ts(2,20): error TS7006: Parameter 'items' implicitly has an 'any' type.
main.ts(2,27): error TS7006: Parameter 'discount' implicitly has an 'any' type.

TS7006 is the most common error of any migration. The fix is the work of migration itself: describe the data. Usually that means an interface for the shapes and annotations on parameters, while local variables keep relying on inference:

TypeScript The same function, migrated

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Giving discount a default value both makes it optional and lets TypeScript infer number. Adding readonly to the array is free documentation that the function doesn't modify its input.

Patterns that JavaScript allows and TypeScript questions

A few JavaScript habits produce errors almost every time. The next example collects two of the most frequent ones and fails on purpose:

TypeScript Two classic migration errors (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(3,10): error TS2339: Property 'theme' does not exist on type '{}'.
main.ts(7,14): error TS2531: Object is possibly 'null'.

The first error happens because TypeScript infers the type of settings from its initializer, {}, an object with no known properties. The second is strictNullChecks doing its job: URLSearchParams.get() returns string | null, so the parameter might be missing. And even when it's present, the JavaScript version had a second bug: '2' + 1 is the string '21', not 3. Fixing the type error forces you to fix both. Here are the fixes:

TypeScript Fixing the classic errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Other errors you'll meet often during a migration, with their usual fixes:

  • TS2345 / TS2322 (argument or value not assignable): often a real bug, like a number passed as a string. Fix the call site or widen the type deliberately.
  • TS2339 on an object that came from JSON.parse or an untyped library: the value is any or {}. Describe it with an interface and validate it (see custom type guards).
  • TS18048 / TS2532 (possibly undefined): optional properties and array lookups. Use ?., ??, or a guard clause.
  • TS7016 (Could not find a declaration file for module 'x'): install @types/x or write a small declaration (see declaration files).

Suppressing errors: @ts-expect-error vs @ts-ignore

Sometimes you can't fix an error today. Maybe the real fix belongs to another team, or the file will be rewritten next sprint. TypeScript has two comments that silence the error on the next line:

TypeScript Two ways to silence an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program compiles and prints string 8080 and string 30s. Both comments hid a real bug: the variables are typed number but hold strings. Suppression comments never change runtime behavior, they only stop the checker from telling you.

The difference shows up once the problem is fixed. A @ts-expect-error with no error below it is itself an error, so it can never go stale. This example fails on purpose, after someone fixed the value but forgot the comment:

TypeScript A stale @ts-expect-error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(1,1): error TS2578: Unused '@ts-expect-error' directive.

A stale @ts-ignore would stay silent forever, and would quietly hide any new error that appears on that line later. Follow these rules in a migration:

  • Prefer @ts-expect-error over @ts-ignore, always. Many teams enforce this with the typescript-eslint rule ban-ts-comment (see tooling).
  • Add a reason after the directive, like the examples above. It turns the comment into a searchable to-do list.
  • // @ts-nocheck at the top of a file disables checking for the whole file. It's a reasonable temporary state for a huge legacy file you have just renamed, but track those files and remove the comment as you fix them.

Don't reach for any or as to make errors disappear either. const data = legacy() as any turns off checking for everything that touches data, and it spreads: every value read from an any is also any. A suppression comment at least stays on one line.

Untyped boundaries: any versus unknown

During a migration, your new TypeScript code constantly calls old JavaScript that returns values TypeScript can't describe well. If those values come back as any, checking silently stops at the boundary. Typing them as unknown instead forces the new code to check what it actually received:

TypeScript any leaks, unknown protects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The any version compiles even though loose.profile doesn't exist, and the program crashes when it runs. The unknown version can't touch the value until the type guard proves its shape. At migration boundaries, assign untyped results to unknown (or to a precise interface plus a runtime check), and you contain the uncertainty instead of spreading it. The any, unknown and never lesson covers the difference in depth.

Turning strictness up in steps

You don't have to enable every strict check on day one. A common sequence for a large codebase looks like this:

Stage Settings What it achieves
1 allowJs: true, strict: false Project builds; TS files can import JS files
2 checkJs: true (or // @ts-check per file) JavaScript is checked using inference and JSDoc
3 noImplicitAny: true Every value has a real or explicit type
4 strictNullChecks: true null and undefined bugs show up; usually the biggest stage
5 strict: true Remaining strict flags (function types, this, catch variables, ...)
6 noUncheckedIndexedAccess, exactOptionalPropertyTypes Extra safety for indexes and optional properties

Each stage is a separate pull request, or several. Flags that produce hundreds of errors can be enabled for new code first: some teams keep a second tsconfig.strict.json that includes only converted folders, and run both in CI. The strict mode lesson shows the bug each flag catches, which helps you explain to your team why the work is worth it.

File extensions and modules

Renaming is mostly mechanical, with a few rules worth knowing:

  • .js becomes .ts, .jsx becomes .tsx, .mjs becomes .mts, .cjs becomes .cts.
  • With "module": "nodenext", relative imports keep the JavaScript extension: import { cartTotal } from './cart.js' even though the file on disk is cart.ts. TypeScript maps it for you. (TypeScript 5.7 added rewriteRelativeImportExtensions for projects that prefer writing ./cart.ts.) Bundler projects with "moduleResolution": "bundler" can usually omit extensions. Modules explains both modes.
  • Convert require() and module.exports to import and export while you're there. TypeScript understands CommonJS, but ES modules give much better type information and are the standard (see JavaScript modules).
  • Libraries without types need @types/... packages or a small .d.ts file. Search npm for @types/<name> first.

A migration plan that works

Here's an order that keeps the app shipping the whole time:

  1. Add TypeScript as a checker. Install typescript, add a tsconfig.json with allowJs, noEmit and strict: false, and run tsc in CI. Nothing changes at runtime.
  2. Install type packages for your dependencies (@types/node, @types/express, ...).
  3. Write shared types first. Create types.ts with interfaces for your core data: users, orders, API responses. Everything else will use them.
  4. Convert from the leaves inward. Start with modules that import nothing else of yours (utilities, formatters, constants), then the code that depends on them. Each converted file gives better types to everything that imports it.
  5. Type the boundaries. API responses, JSON.parse, environment variables and form input are unknown until validated.
  6. Raise strictness in the stages from the table above, fixing errors folder by folder.
  7. Ban new JavaScript. Once most files are converted, turn off allowJs and remove leftover @ts-nocheck and @ts-expect-error comments.

Automated tools such as Airbnb's ts-migrate can rename files in bulk and insert any and suppression comments so the project compiles immediately. That gets you to .ts fast, but every inserted any is a hole to fill later, so treat the output as a starting point rather than a finished migration.

Measure progress with numbers your team can see: the count of .js files left, @ts-expect-error comments, and explicit anys (typescript-eslint's no-explicit-any rule can count them). Seeing those numbers drop each week keeps a long migration moving.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does adding // @ts-check to the top of a .js file do?

    @ts-check enables checking for one JavaScript file, like checkJs does for all of them. The file stays JavaScript; JSDoc comments supply the types.
  2. 2. In strict mode, what does function area(w, h) { return w * h; } produce in a .ts file?

    noImplicitAny (part of strict) refuses to silently type unannotated parameters as any, so you get TS7006 for each one.
  3. 3. A line is preceded by a ts-expect-error comment, and later someone fixes the error on that line. What happens?

    That is the main advantage over ts-ignore. A stale ts-expect-error is reported, so suppression comments cannot pile up unnoticed.
  4. 4. Which type should new TypeScript code use for the result of an untyped legacy JavaScript function?

    unknown forces you to narrow the value before using it, so wrong assumptions are caught. any silently disables checking for everything it touches.
  5. 5. With module nodenext, how does src/app.ts import src/cart.ts?

    Node's ESM resolution needs a full file name, and the file that will exist at runtime is cart.js, so you write the .js extension and TypeScript maps it to cart.ts.

Summary

  • Migrate gradually: allowJs lets .ts and .js files live together, and noEmit lets tsc act purely as a checker.
  • // @ts-check or checkJs type-checks JavaScript files, with JSDoc tags (@type, @param, @typedef, @template, @import) supplying the types.
  • Renaming a file to .ts usually surfaces TS7006 (implicit any), TS2339 (objects built step by step) and null-safety errors. Fix them with interfaces, parameter annotations and explicit null handling.
  • Prefer @ts-expect-error to @ts-ignore: it reports TS2578 once the error is gone. Give every suppression a reason, and use @ts-nocheck only temporarily.
  • Treat values from untyped code as unknown and validate them, instead of letting any spread.
  • Raise strictness in stages (noImplicitAny, then strictNullChecks, then full strict), convert from the leaves inward, and track the remaining JavaScript files and suppressions.

Next: Promises and async/await