Tutorials / TypeScript: Beginner to Advanced / Migrating a JavaScript project to TypeScript

Migrating a JavaScript project to TypeScript

18 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

Do not rewrite everything

The wrong way to migrate is to stop all work for a week, rename every file to .ts and fight 3000 errors. The right way is gradual. TypeScript is designed so that JavaScript and TypeScript files can live side by side, and so that you can raise the strictness in steps. Your project keeps working and shipping the whole time.

This is the process I would follow.

Step 0: get your safety net ready

Before touching types, make sure you have something that tells you whether the app still works, even if it is only a few tests and a manual checklist. Commit your starting point. Make sure the current code builds, lints and runs.

Step 1: add TypeScript and a tolerant tsconfig

npm install --save-dev typescript

Create tsconfig.json. At first, the goal is to let TypeScript read your JavaScript without complaining:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "allowJs": true,
    "checkJs": false,
    "noEmit": true,
    "strict": false,
    "skipLibCheck": true
  },
  "include": ["src"]
}

allowJs lets .js files take part in the program. checkJs: false means JavaScript files are not checked yet. strict: false keeps the rules loose. With noEmit, your existing build tool still produces the output, and TypeScript only checks. Add a typecheck script: "typecheck": "tsc --noEmit". It should pass right away.

Step 2: install types for your dependencies

npm install --save-dev @types/node

Add @types/... packages for libraries that need them, such as @types/express or @types/react. This alone gives you much better editor help in JavaScript files.

Step 3: check JavaScript with checkJs and JSDoc

You can start finding bugs without renaming anything. Turn on checking for the whole project with "checkJs": true, or for individual files, by putting // @ts-check at the top. Type information is added with JSDoc comments:

// @ts-check

/**
 * @param {number} price
 * @param {number} quantity
 * @returns {number}
 */
export function total(price, quantity) {
  return price * quantity;
}

/** @typedef {{ id: number, name: string, email?: string }} User */

/** @param {User} user */
export function label(user) {
  return `${user.name} <${user.email ?? "no email"}>`;
}

TypeScript understands these comments and checks the code, and the files are still valid JavaScript. This is a good way to start on a team that is not ready to commit to .ts files yet, or in files you do not want to rename for now. Many people stop here for files that rarely change.

Step 4: convert files one by one

Begin with the leaves of your dependency tree: utility functions, constants, and data helpers that import nothing from your project. Their types are easy, and they unlock the typing of the files that import them. Then move up towards the entry points.

For each file:

  1. Rename .js to .ts (or .jsx to .tsx) with git mv to keep the history.
  2. Fix the import paths if your setup requires it.
  3. Add types to function parameters and exports. Let inference do the rest.
  4. Define interfaces for your main data objects, such as User, Order, Product, in a shared types.ts file.
  5. Run npm run typecheck and fix what it reports.
  6. Commit. One file or one folder per commit makes review easy.

Step 5: handle the awkward bits

You will meet patterns that do not fit neatly:

  • Objects built up in steps. const config = {}; config.port = 80; fails because config has no port. Build the object in one expression, or declare an interface and use Partial.
  • Functions with several shapes of input. Use union types and narrowing, or overloads.
  • Dynamic keys. Use Record<string, T> or a mapped type.
  • Code you cannot type yet. Use unknown first. If you need a temporary escape, use any with a // TODO(types) comment, so you can search for it later, or @ts-expect-error with a reason.
  • Event handlers and DOM code. Types such as HTMLInputElement and MouseEvent come from the DOM library, which is included by default.
const input = document.querySelector<HTMLInputElement>("#email");
if (input) {
  input.addEventListener("input", (event: Event) => {
    const target = event.target as HTMLInputElement;
    console.log(target.value);
  });
}

The generic form of querySelector returns the right element type, or null, so you must check for null first.

Step 6: tighten the rules

When most files are converted, raise strictness in this order:

  1. noImplicitAny. Fix the places where types are missing.
  2. strictNullChecks. This normally produces the most errors, and finds the most real bugs.
  3. The remaining parts of strict, then replace all with "strict": true.
  4. Optionally, noUncheckedIndexedAccess and the other extra flags.

Do each in its own commit or pull request. If a flag produces hundreds of errors, fix one folder at a time. Some teams use a tool such as typescript-strict-plugin, or the // @ts-strict-ignore pattern, to opt the old files out while new files are strict. A rule I like: new code must be strict, and old code gets stricter whenever someone touches it.

Step 7: switch the build, and guard it in CI

Finally, make tsc --noEmit part of your continuous integration, so type errors fail the build. If you want tsc to produce the output now, set noEmit to false and configure outDir. If a bundler does the build, keep noEmit and keep the check as a separate step.

A realistic timeline

For a small app of 20 to 50 files, one developer can do the whole thing in a few days alongside normal work. For a big code base, it takes weeks or months, and that is fine, because every step along the way is a working application.

Common mistakes

  • Converting everything at once. The pull request becomes unreviewable and the project stalls.
  • **Leaving any everywhere and calling it done.** Track the any count and reduce it.
  • **Casting with as to remove errors.** You keep the bug and lose the warning.
  • Typing the data too early and getting it wrong. Check the real shape of API responses before you write the interface.
  • Not running the type check in CI. The errors return silently.
  • **Renaming files without git mv.** You lose the file history.

Try it yourself

  1. Take a small JavaScript project, add TypeScript with allowJs and noEmit, and make npm run typecheck pass.
  2. Add // @ts-check and JSDoc types to one file and fix the errors it reveals.
  3. Convert two leaf files to .ts with proper interfaces.
  4. Turn on noImplicitAny and count how many errors appear. Fix the ones in a single folder.
typescript
const input = document.querySelector<HTMLInputElement>("#email");
if (input) {
  input.addEventListener("input", (event: Event) => {
    const target = event.target as HTMLInputElement;
    console.log(target.value);
  });
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account