HomepageExploring TypeScript (TS 5.8 Edition)
You can support this book: buy it or donate
(Ad, please don’t block.)

12 Strategies for migrating to TypeScript

This chapter gives an overview of strategies for migrating code bases from JavaScript to TypeScript. It also mentions material for further reading.

12.1 Strategy: mixed JavaScript/TypeScript code bases

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:

12.2 Strategy: adding type information to plain JavaScript files

This approach works as follows:

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) {
  return x + y;
}
/** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType */
/** @typedef {(data: string, index?: number) => boolean} Predicate */

More information:

12.3 Strategy: linting before activating a compiler option

Projects that migrate to TypeScript often start with the default type checking and then add more checks, in stages – e.g.:

  1. Initially: default checks
  2. Activate strictNullChecks (prevents undefined and null from being used unless the type is T | undefined or T | null, respectively)
  3. Activate noImplicitAny (prevents omitting types for parameters and more)
  4. Activate strict (includes the previous two compiler options – which can be removed – and adds additional ones)

In contrast to compiler options, we can activate linting options on a per-file basis. This helps when switching from less strict type checking to stricter type checking: We can lint before making the switch. These are examples of useful rules that the TypeScript linter typescript-eslint provides:

12.4 Strategy: Too many errors? Use snapshot testing

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:

12.5 Tools that help with migrating to TypeScript

12.6 Conclusion and further reading

We have taken a quick look at strategies for migrating to TypeScript. Two more tips:

Further reading: