This chapter gives an overview of strategies for migrating code bases from JavaScript to TypeScript. It also mentions material for further reading.
These are three strategies for migrating to TypeScript:
We can support a mix of JavaScript and TypeScript files for our code base. We start with only JavaScript files and then switch more and more files to TypeScript.
We can keep our current (non-TypeScript) build process and our JavaScript-only code base. We add static type information via JSDoc comments and use TypeScript as a type checker (not as a compiler). Once everything is correctly typed, we switch to TypeScript for building.
For large projects, there may be too many TypeScript errors during migration. Then snapshot tests can help us find fixed errors and new errors.
More information:
The TypeScript compiler supports a mix of JavaScript and TypeScript files if we use the compiler option --allowJs
:
At first, there are only JavaScript files. Then, one by one, we switch files to TypeScript. While we do so, our code base keeps being compiled.
This is what tsconfig.json
looks like:
{
"compilerOptions": {
···
"allowJs": true
}
}
More information:
This approach works as follows:
--noEmit
). In addition to the compiler option --allowJs
(for allowing and copying JavaScript files), we also have to use the compiler option --checkJs
(for type-checking JavaScript files)..js
files to .ts
files is not urgent now because the whole code base is already fully statically typed. We can even produce type files (filename extension .d.ts
) now.This is how we specify static types for plain JavaScript via JSDoc comments:
/**
* @param {number} x - The first operand
* @param {number} y - The second operand
* @returns {number} The sum of both operands
*/
function add(x, y) {
+ y;
return x }
/** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType */
/** @typedef {(data: string, index?: number) => boolean} Predicate */
More information:
§4.4 “Using the TypeScript compiler for plain JavaScript files”
“How we gradually migrated to TypeScript at Unsplash” by Oliver Joseph Ash
In large JavaScript projects, switching to TypeScript may produce too many errors – no matter which approach we choose. Then snapshot-testing the TypeScript errors may be an option:
More information:
We have taken a quick look at strategies for migrating to TypeScript. Two more tips: