Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Workflow recipe

Migrate a JavaScript project to TypeScript with a coding agent

allowJs first, convert files leaves first in worktree batches, then raise strictness one flag at a time.

By Checked Intermediate2 h 25 min7 steps
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On this page

To migrate JavaScript to TypeScript with AI, add TypeScript with allowJs and strict off so nothing breaks, list your modules in dependency order, and have a coding agent convert them leaves first in small batches, each on its own branch or worktree, with the test suite and tsc as the gate for every batch. Then turn strictness on one flag at a time, let the agent fix only the errors it can prove are safe, and decide the rest yourself, because those are usually real bugs.

Asking an agent to “convert the project to TypeScript” in one go gives you a huge diff full of any, casts and @ts-ignore that type-checks and hides every problem the migration was meant to find. When we ran this recipe on a small invoicing module, the batched approach with a strict prompt produced no any at all, and turning on strictNullChecks raised four errors: two the agent fixed safely, and two real bugs (an unknown customer crashed total(), and a blank price was billed as £0 without a warning). That list of bugs is the most valuable thing the migration produces, and it only appears if you forbid the shortcuts.

TerminalAbout 10 min

1. Record a green baseline on a branch

Start from a clean branch and prove the tests pass before anything changes. Write down the test count; every later batch must match it.

git switch -c ts-migration
npm test

We had # pass 6 and # fail 0. If the baseline fails, fix that first, or you will not know whether a failure came from the migration. If your project has thin tests, add a few around the code you care about first, using unit tests for legacy code: during a migration the tests are the only proof that behaviour did not change.

TerminalAbout 15 min

2. Add TypeScript with allowJs and strict off

Install TypeScript and Node’s types, then write tsconfig.json by hand rather than with tsc --init, so you control every flag.

npm install --save-dev typescript @types/node
npm pkg set scripts.typecheck="tsc -p ."
{
  "compilerOptions": {
    "module": "nodenext",
    "target": "es2023",
    "types": ["node"],
    "noEmit": true,
    "allowJs": true,
    "checkJs": false,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "strict": false,
    "skipLibCheck": true
  },
  "include": ["src", "test"]
}

allowJs lets .js and .ts files import each other while you convert, so the project works at every commit. Our project runs .ts files directly with Node’s type stripping, which is why it has noEmit, allowImportingTsExtensions (imports name the .ts file) and erasableSyntaxOnly (no enums or namespaces, which Node cannot strip). If you build with a bundler or emit JavaScript with tsc, drop those three and keep the rest.

Run npm run typecheck and npm test. Both should pass with nothing converted yet; ours did, with tsc taking under half a second. Commit.

Claude CodeAbout 10 min

3. List the modules in dependency order and plan the batches

Convert leaves first: a file that imports nothing from your project can be typed on its own, and the files that import it then get real types instead of guesses. Ask the agent for the order without changing anything.

Dependency order and batches · Claude Code or Codex
Read the project's source and test files. Do not edit anything. 1. List every source file with the project files it imports. 2. Sort them into layers: layer 0 imports no project files, layer 1 imports only layer 0, and so on. Flag any import cycles. 3. Propose batches of one to three files. Files in the same batch must be in the same layer. Mark which batches could run in parallel because no two of them are imported by the same file. 4. Name the test files that import each source file.

In plan mode it took 21 seconds and returned four files in three layers: money.js and customers.js (layer 0), invoice.js (layer 1) and report.js (layer 2), no cycles, and one test file importing all four. It also said no batches could run in parallel, because invoice.js and the test file import both layer-0 files. We split layer 0 into two parallel batches anyway, to see what that costs; step 5 shows the answer.

Claude Code or Codex, in worktreesAbout 30 min

4. Convert the first batches with a strict prompt, one worktree each

Give each parallel batch its own git worktree and branch, so two agents never edit the same checkout. Each worktree needs its own npm ci.

git worktree add -b ts/batch-1 ../app-ts-batch-1
git worktree add -b ts/batch-2 ../app-ts-batch-2
(cd ../app-ts-batch-1 && npm ci)
(cd ../app-ts-batch-2 && npm ci)

Then run the conversion prompt in each worktree, with the batch’s files in the slot.

Convert one batch, no shortcuts · Claude Code or Codex
Convert these files from JavaScript to TypeScript: [FILES IN THIS BATCH] tsconfig.json has allowJs on and strict off for now; strictness will be raised later. Rules: - Rename each file with git mv so its history follows it. Update relative imports that point at a renamed file, in every file that imports it. - Add types for parameters, return values and the shapes of objects that cross module boundaries. Put shared types in the file that owns the data and export them. - Do not change runtime behaviour. No refactoring, renaming or reformatting of lines you do not need to touch. - Do not use any, as any, as unknown as, @ts-ignore, @ts-expect-error or non-null assertions (!). If a type cannot be written without one of these, stop and tell me which line and why. - In tests, change only import paths that point at a renamed file. Do not edit anything else in tests, and do not edit tsconfig.json or package.json. - After the change, run [TYPECHECK COMMAND] and [TEST COMMAND]. Both must pass. If either still fails after three attempts, stop and report what you tried. Report: each file you converted, each exported type you added, any place where the types revealed a possible bug (do not fix it, list it), and the final output of both commands.

Run it interactively, or headless so both batches run at once. Allow only the commands the batch needs:

cd ../app-ts-batch-1
claude -p "$(cat convert-prompt.txt)" --permission-mode acceptEdits \
  --allowedTools "Bash(npm run typecheck)" "Bash(npm test)" "Bash(git mv:*)"

Our two batches took 35 and 45 seconds. The reports listed the exported types (Customer, NewCustomer, Pence) and possible bugs: vatRateFor() reads .vatRate from a customer that may not exist, and parseAmount("") returns null, which subtotal silently treats as 0. Read the diff of each batch, then commit it in its worktree.

Terminal and Claude CodeAbout 30 min

5. Merge the batches, then convert the next layer

Merge the parallel branches one at a time and run both gates after each merge.

git merge ts/batch-1
git merge ts/batch-2
npm run typecheck && npm test

Our second merge conflicted, as the plan predicted. Both batches had changed adjacent import lines in invoice.js and in the test file (one changed money.js to money.ts, the other customers.js to customers.ts), and Git will not merge changes to neighbouring lines on its own. The fix is mechanical: keep both new paths. To avoid it, follow the plan and only run batches in parallel when no file imports from both, or accept the small conflict as the price of the speed.

Then run the same conversion prompt on the next layer, on the main migration branch. Our layer 1 and 2 batch (invoice.js and report.js) took 74 seconds and added Invoice, InvoiceLine, InvoiceItem and SentInvoice types, with report.ts importing Invoice through import type. Remove the worktrees when the merges are in: git worktree remove ../app-ts-batch-1.

Claude CodeAbout 30 min

6. Raise strictness one flag at a time

With every file converted and strict off, measure what each flag would raise before you switch it on:

npx tsc -p . --noImplicitAny
npx tsc -p . --strictNullChecks
npx tsc -p . --strict

We got 0, 4 and 4 errors. Turn on the flag with errors and have the agent sort them into safe fixes and real bugs, rather than making them all go away.

Raise one flag, separate safe fixes from bugs · Claude Code or Codex
We are raising TypeScript strictness one flag at a time. Set "[FLAG]": true in tsconfig.json and run [TYPECHECK COMMAND]. For each error, decide which kind it is and say so: - SAFE: the value cannot be null or undefined at runtime, and you can show why from the code. Fix it with a narrowing check or a better type that keeps the same behaviour. - BUG: the value can be null or undefined at runtime with some input, and today the code then crashes or gives a wrong result. Do not fix these. List them with the file and line, an input that triggers it, what happens today, and two options for the intended behaviour. Rules: - No any, no non-null assertions (!), no @ts-ignore or @ts-expect-error, no casts that hide null. - Do not change runtime behaviour for any SAFE fix. Do not edit tests. - Run [TYPECHECK COMMAND] and [TEST COMMAND] at the end. Typecheck will still fail on the BUG errors; that is expected. Tests must pass. Report a table: file:line, SAFE or BUG, what you did or the options, then the final output of both commands.

Ours took about a minute. It fixed two errors as SAFE: addCustomer now returns the object it stored instead of reading it back from the Map, and Invoice became a union so a sent invoice always has a sentOn date. It left two as BUG, each with an input that triggers it: total() for an unknown customer throws a TypeError, and a blank price is billed as £0.00. Each bug is a product decision, so make it yourself: the agent offered a clear Unknown customer error or a default VAT rate for the first, and rejecting blank prices or marking the invoice incomplete for the second. Add a test for the behaviour you choose, fix it, and commit when the flag passes. Then do the same for strict and, if you want it, noUncheckedIndexedAccess; measuring that flag in our project showed one more real bug, toCsv([]) crashing on an empty list.

TerminalAbout 20 min

7. Review the whole migration for hidden escapes

The point of the rules was to keep the escape hatches out. Check that they stayed out, and that behaviour did not change.

git diff main --stat
git grep -nE ": any\b|as any|as unknown as|@ts-ignore|@ts-expect-error|\w!\." -- 'src/*.ts'
git diff main -- test/
npm run typecheck && npm test

Red flags: any match from the search, a test changed beyond an import path, a .d.ts file nobody asked for, skipLibCheck or strict flipped by the agent, or a behaviour change mixed into a “types only” commit. Our search found nothing, the test diff was four import lines, and the test count matched step 1. Write the bugs the agent listed into the pull request description, with what you decided for each, so reviewers see what the migration changed on purpose.

Check it worked

Verification checklist

0 of 6 done

When it goes wrong

If the agent stops and says the rules conflict, read why before you override it. Our first prompt said “do not edit tests”, and every batch stopped because the test file imports the renamed .js path and Node will not resolve money.js to money.ts. The agent was right; the rule was wrong. We changed it to “in tests, change only import paths”, which is the version above.

If a batch cannot be typed without importing a type from a file that is still JavaScript, the batch is out of order. Our first plan put report.js in a parallel batch, and the agent stopped because its Invoice type had to come from invoice.js. Convert in the dependency order from step 3, or let the agent declare a small local type and move it later.

If parallel batches conflict on merge, it is usually adjacent import lines in a shared importer, as ours did. Resolve by keeping both new paths, then run both gates. If conflicts reach real code, the batches were not independent; merge sooner and batch smaller.

If a “safe” fix changes what a function returns, it was not safe. Our SAFE fix to addCustomer returned the stored object instead of reading it back from the Map; that is the same object, so behaviour held, but check each SAFE row against the test run and the diff rather than trusting the label. Run each batch in a fresh session with the full prompt, so the rules are never far back in the context.

Variations

For a large codebase, run step 6 before step 4 as a measurement: checkJs: true with JSDoc types lets you see type errors in JavaScript files before renaming anything, and some teams stop there. The same batch and gate pattern also works for a framework upgrade; see upgrade a dependency with a coding agent.

With more than three parallel batches, use the worktree routine in parallel refactors with git worktrees, and the Using Git worktrees skill to keep each agent in its own checkout. The Verification before completion skill stops an agent from reporting a batch done without showing the command output.

In CI, add npm run typecheck as a required check as soon as step 2 is merged, so nobody adds new untyped code while the migration is under way. Running the batches as unattended jobs is covered in the headless coding agents in CI tutorial.

The AI-assisted software engineering path covers the habits this recipe relies on: plans before edits, tests as the gate and review of every agent diff. Before you approve the migration pull request, read how to review AI-written code.

Outcome and tools

Outcome
A project whose source files are TypeScript, type-checked with strictNullChecks on, tests still green, and a written list of the bugs the types exposed.
For
Developers
Variants for
Claude Code, Codex
  • Refactor in parallel with git worktrees and two agents

    Use git worktrees to run Claude Code and Codex in parallel on the same refactor from one written plan, compare tests, diff size and readability, then merge one.

    WorkflowAdvanced1 h 30 min6 steps

  • Upgrade a dependency with an AI coding agent, without surprises

    Get an impact list from the migration guide, bump on a branch, let the agent fix with guardrails, then compare old and new output.

    WorkflowIntermediate1 h 15 min6 steps

  • Write unit tests for legacy code with a coding agent

    An agent writes characterisation tests, you check for weak assertions and prove them with mutation testing.

    WorkflowBeginner1 h6 steps

  • Git worktree

    An extra working directory attached to the same Git repository, with its own branch checked out, created with `git worktree add`.

    Glossary

  • AI-assisted software engineering

    Learn AI-assisted software engineering on real repositories: set up coding agents, give them good instructions, review their diffs and run several in parallel.

    Learning pathIntermediate11 h14 steps

Back to top