This blog post 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 continue to use plain JavaScript and add type information via JSDoc comments until everything if fully typed. At that point, we switch to TypeScript.
For large projects, there may be too many TypeScript errors during migration. Then snapshot tests for the errors can help.
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
)..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 - A number param.
* @param {number} y - A number param.
* @returns {number} This is the result
*/
function add(x, y) {
return x + y;
}
/** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType */
/** @typedef {(data: string, index?: number) => boolean} Predicate */
More information:
“Type-Checking JavaScript Files” in the TypeScript Handbook
“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 various strategies for migrating to TypeScript. Two more tips:
What have your experiences been when you migrated code bases from JavaScript to TypeScript? Let us know in the comments!