Migrating a JavaScript project to TypeScript
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- 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:
- Rename
.jsto.ts(or.jsxto.tsx) withgit mvto keep the history. - Fix the import paths if your setup requires it.
- Add types to function parameters and exports. Let inference do the rest.
- Define interfaces for your main data objects, such as
User,Order,Product, in a sharedtypes.tsfile. - Run
npm run typecheckand fix what it reports. - 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 becauseconfighas noport. Build the object in one expression, or declare an interface and usePartial. - 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
unknownfirst. If you need a temporary escape, useanywith a// TODO(types)comment, so you can search for it later, or@ts-expect-errorwith a reason. - Event handlers and DOM code. Types such as
HTMLInputElementandMouseEventcome 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:
noImplicitAny. Fix the places where types are missing.strictNullChecks. This normally produces the most errors, and finds the most real bugs.- The remaining parts of
strict, then replace all with"strict": true. - Optionally,
noUncheckedIndexedAccessand 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
anyeverywhere and calling it done.** Track theanycount and reduce it. - **Casting with
asto 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
- Take a small JavaScript project, add TypeScript with
allowJsandnoEmit, and makenpm run typecheckpass. - Add
// @ts-checkand JSDoc types to one file and fix the errors it reveals. - Convert two leaf files to
.tswith proper interfaces. - Turn on
noImplicitAnyand count how many errors appear. Fix the ones in a single folder.
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