21 August 2023
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.
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.
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.
Starting a new TypeScript project is straightforward. We need:
package.json
file to manage dependenciestsconfig.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!
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.
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.
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.
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:
tsc
to compile .ts
=> .js
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.
Migrating JavaScript to TypeScript takes a bit of work but pays off in the long run with more robust code. The key steps are:
.js
files to .ts
incrementallytsc
and bundlersTypeScript'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.
It depends on the size but plan on incrementally converting files over several weeks. Budget adequate time for testing and resolving issues.
You can still use it by declaring types like declare module "lib"
. As a last resort, types can be suppressed via any
.
Yes, TypeScript interfaces very well with JavaScript. You can incrementally convert files while keeping everything interoperable.
Rewriting from scratch is risky. Focus on getting to TypeScript incrementally while changing legacy code when needed.
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
CONTACT
+44 (0)20 8446 7555
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