CUSTOMISED
Expert-led training for your team
Dismiss
How to Migrate from JavaScript to TypeScript

21 August 2023

How to Migrate from JavaScript to TypeScript

TypeScript has rapidly grown in popularity as a way to create more robust JavaScript applications. This guide covers the key steps involved in migrating an existing JavaScript codebase to TypeScript.

JBI Training offers a complete solution to all of your Typescript Training requirements. To train a team, customise a course or find out more simply get in touch and our dedicated advisors will be happy to help. 

Introduction

TypeScript extends JavaScript syntax with type annotations and other features like classes and interfaces. The additional type information allows catching errors during development rather than at runtime.

TypeScript logo

With over 50% of JavaScript developers now utilizing TypeScript, migrating JavaScript projects can help improve maintainability and catch bugs earlier.

Let's go through the migration process step-by-step.

Setting Up a TypeScript Project

Starting a new TypeScript project is straightforward. We need:

  • Node.js installed for the Node Package Manager (NPM)
  • A package.json file to manage dependencies
  • TypeScript installed as a dev dependency
  • A TypeScript config file tsconfig.json

Let's init a new NPM project:

npm init -y

Install the TypeScript compiler:

npm install --save-dev typescript

Add a tsconfig.json:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs", 
    "strict": true
  }
}  

That's the basics to start writing TypeScript code!

Porting JavaScript Files to TypeScript

With the project setup, we can incrementally convert .js files to .ts and introduce types.

For example, we may start with a simple math.js module:

// math.js

export function sum(a, b) {
  return a + b;
}

export function square(x) {
  return x * x;
} 

We can port this to TypeScript keeping the same functionality:

// math.ts

export function sum(a: number, b: number) {
  return a + b; 
}

export function square(x: number) {
  return x * x;
}

TypeScript can infer types like arrays:

// utils.js 

export function first(arr) {
  return arr[0];
}
// utils.ts

export function first(arr: any[]) {
  return arr[0]; 
}

We can gradually annotate more types while remaining compatible with consumers of the JavaScript code.

Handling Incompatible APIs

Sometimes JavaScript code patterns like variable reassignment need refactoring to work with TypeScript's stricter checks.

For example, this function mutates an object input:

// source data
let user = {
  name: "Alice",
  age: 32  
};

function updateUser(user) {
  user.name = "Bob"; // mutate input
  user.age = 25;
}

updateUser(user);

TypeScript will complain here because the user parameter cannot be safely mutated.

We can update it to return a new user object:

interface User {
  name: string;
  age: number;
}

function updateUser(user: User): User {
  return {
    ...user, 
    name: "Bob",
    age: 25
  };   
}

const user = {
  name: "Alice",
  age: 32
};

const updatedUser = updateUser(user);

This captures the intent better and avoids mutating the inputs.

Leveraging Type Declarations

Many JavaScript libraries have TypeScript declaration files available which describe the types of objects like React and jQuery.

We can install these as @types/react and get full type checking and auto-complete when using them:

import React from "react";

function App() {
  const [count, setCount] = React.useState(0); // typed hooks

  return <div>{count}</div>; // typed jsx
}

Declarations for popular libraries are available on DefinitelyTyped.

Configuring a Build Pipeline

We'll need a pipeline to transpile the TypeScript code to JavaScript that can run in the browser or Node.js.

A common approach is:

  1. Use tsc to compile .ts => .js
  2. Bundle with Webpack, Rollup, or Parcel
  3. Include source maps to assist debugging

For Node.js, we can compile on the fly without bundling.

Make sure to configure your IDE to run tsc on file changes so errors surface immediately during development.

Conclusion

Migrating JavaScript to TypeScript takes a bit of work but pays off in the long run with more robust code. The key steps are:

  • Setting up a TypeScript project
  • Converting .js files to .ts incrementally
  • Using type declarations for libraries
  • Building a pipeline with tsc and bundlers

TypeScript's familiar syntax makes it easy for JavaScript teams to adopt. Focus on the highest value areas first during a migration. Over time it can improve any JavaScript codebase.

Frequently Asked Questions

How long does it take to migrate a codebase to TypeScript?

It depends on the size but plan on incrementally converting files over several weeks. Budget adequate time for testing and resolving issues.

What if a library doesn't have TypeScript declarations?

You can still use it by declaring types like declare module "lib". As a last resort, types can be suppressed via any.

Can I mix TypeScript and JavaScript files?

Yes, TypeScript interfaces very well with JavaScript. You can incrementally convert files while keeping everything interoperable.

Should I rewrite legacy code instead of migrating?

Rewriting from scratch is risky. Focus on getting to TypeScript incrementally while changing legacy code when needed.

What if my project uses ES5 JavaScript features?

TypeScript can target ES5 and beyond. Your JavaScript features won't be blocked.

If you enjoyed this article you might like to read How to code in typescript

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course