TypeScript · Lesson 40 of 42
Migrating a JavaScript project to TypeScript
Move a JavaScript project to TypeScript gradually with allowJs, checkJs, JSDoc, strict flags one at a time and @ts-expect-error.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will know how to bring TypeScript into a project that already exists, without stopping the team or breaking the product. Most real-world adoption is a migration, not a fresh start, and a careful, incremental approach is what makes it succeed.
The principle: coexist, then convert
Do not try to convert everything at once. A big rewrite is risky, slows the team, and mixes behaviour changes with typing changes. Instead, set the project up so JavaScript and TypeScript live side by side, then convert one file at a time, starting wherever it gives the most benefit. At every step the project still builds and the tests still pass.
Step 1: add TypeScript and a loose configuration
Install the compiler and create a tsconfig.json that accepts your existing code:
{
"compilerOptions": {
"target": "ES2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"allowJs": true,
"checkJs": false,
"noEmit": true,
"strict": false,
"skipLibCheck": true
},
"include": ["src"]
}allowJs lets TypeScript files import JavaScript files and vice versa. With checkJs off, the JavaScript files are not checked yet, so the compiler is quiet. strict is off, because turning it on now would flood you with errors. If your tools already turn your code into JavaScript, such as a bundler, keep them and use noEmit so tsc only checks types.
Step 2: get safety in JavaScript before renaming
Even before you rename a file, TypeScript can check it, using JSDoc comments as type annotations. Add // @ts-check at the top of a single file, or set checkJs: true for all of them. For example, in a JavaScript file:
// @ts-check
/**
* @param {number} price
* @param {number} rate
* @returns {number}
*/
function addTax(price, rate) {
return price * (1 + rate);
}
addTax("19.99", 0.2);The compiler reports the wrong argument type in the .js file, exactly as it would in a .ts file. JSDoc types support most of TypeScript's type language, including @type, @typedef and generics. This route needs no renaming and no build changes, so it is a gentle first step for files you are not ready to convert.
Step 3: convert files, leaves first
Rename a .js file to .ts and fix the errors it reports. Choose the order wisely:
- Shared types and data shapes first. Create a file of types for your core data, such as users and orders, because everything else will use them.
- Leaf modules that depend on little: utility functions, constants, small helpers.
- Then the modules that use them, working inwards towards the entry point.
Converting dependencies first means each file you convert already has typed imports to lean on. Commit after each file, so a problem is easy to find and revert.
Step 4: handle what you cannot type yet
You will meet code that is hard to type quickly. Use these tools, from best to worst, and always leave a note about why:
unknown, then narrow, for data of uncertain shape.- A
// @ts-expect-errorcomment above a line with a known, accepted error. It is safer than the older// @ts-ignore, because the compiler complains if the line no longer has an error, so stale suppressions do not pile up. anyas a last resort, marked with a comment.
function legacyParse(input: string): number {
// @ts-expect-error the old library returns a string here; fixed upstream in a later version
const value: number = input.trim();
return Number(value);
}
console.log(legacyParse(" 42 "));42The directive tells the compiler to expect an error on the next line. If someone later fixes the problem and the error disappears, the compiler flags the now-unneeded directive:
// @ts-expect-error this used to be a problem
const value: number = 42;
console.log(value);example.ts(1,1): error TS2578: Unused '@ts-expect-error' directive.Step 5: turn strictness up gradually
With most files converted, tighten the settings one flag at a time, fixing each wave of errors before enabling the next. A common order:
noImplicitAny: forces every parameter to have a type.strictNullChecks: usually the biggest wave, and the most valuable. It makes you handlenullandundefined.strictPropertyInitializationand the remainingstrictflags.- Finally, replace the individual flags with
"strict": true, and considernoUncheckedIndexedAccess.
Each flag finds a real class of bugs, so the work pays for itself. If a flag produces thousands of errors in a very large project, some teams enable it for new and converted folders only, using separate tsconfig files, and grow the covered area over time.
Step 6: keep the gains
Once the project is converted, add tsc --noEmit to your continuous integration, so type errors fail the build. New files are written in TypeScript by default. Review any remaining any and @ts-expect-error comments now and then, since each one is a known weak spot. The linting lesson that follows adds automated rules for keeping any under control.
Tips from experience
- Do not change behaviour while adding types. If you find a bug while typing, fix it in a separate commit.
- Do not model the type of a messy structure perfectly at first. An honest, slightly loose type is better than a stalled migration.
- Let the compiler guide you. The errors it reports are a to-do list of places where assumptions were hidden.
- Involve the whole team. Agree on conventions such as
typeversusinterfacebefore many files exist.
Common mistakes
Trying to convert everything at once. Incremental changes keep the project releasable.
Turning on strict first. Start loose and tighten gradually.
Using @ts-ignore everywhere. Prefer @ts-expect-error with an explanation, so stale ones are found.
Letting any spread. An any in a shared utility infects every file that calls it. Type the shared code first.
Forgetting to update CI. Without a type check in CI, errors creep back.
Exercise
Take a small JavaScript project, or write a three-file one. Add a tsconfig.json with allowJs. Add // @ts-check and JSDoc types to one file and fix what it reports. Then rename a second file to .ts, type it, and turn on noImplicitAny. Write down which errors were real bugs and which were only missing types.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.