Home Coding & Scripting Converting Your JavaScript Files into TypeScript

Converting Your JavaScript Files into TypeScript

214
0

If you already have a JavaScript project and want to make it safer and easier to maintain, converting it to TypeScript is a great idea.
The good news? You don’t have to start from scratch. You can gradually add TypeScript — one file at a time!

In this post, you’ll learn a simple, step-by-step way to move your JavaScript project into TypeScript.


🎯 Why Convert to TypeScript?

Before we start, let’s quickly recall why TypeScript is worth the effort:

  • ✅ Catches bugs early — during coding, not at runtime.
  • ✅ Autocompletion and IntelliSense in VS Code.
  • ✅ Better readability and collaboration for large projects.
  • ✅ Gradual migration — you can mix JavaScript and TypeScript safely.

🧩 Step 1: Add TypeScript to Your Project

If you already have a JavaScript project, just install TypeScript using npm (or yarn):

npm install typescript --save-dev

Next, create a TypeScript configuration file called tsconfig.json:

npx tsc --init

This creates a file that tells TypeScript how to compile your code.
You’ll see something like this:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

You can customize these options later, but this is enough to start.


📂 Step 2: Rename .js Files to .ts

Now, take one small step — rename one of your .js files to .ts:

example.js → example.ts

This tells TypeScript to start checking that file for types.
At this stage, TypeScript might show a few errors — don’t panic! It’s doing its job.

If your file contains JSX (React code), rename it to .tsx instead.

App.js → App.tsx

⚙️ Step 3: Fix Any Type Errors Gradually

TypeScript might not understand some parts of your JavaScript yet.
Start small — fix a few errors at a time.

You can help TypeScript by adding explicit types where needed:

Example

Before:

function greet(name) {
  return "Hello, " + name;
}

After:

function greet(name: string): string {
  return "Hello, " + name;
}

This tells TypeScript:

  • name must be a string.
  • The function returns a string.

🧠 Step 4: Use any When You’re Unsure (Temporarily)

If you don’t know a variable’s type yet, use any as a placeholder.
This lets you move forward and clean it up later.

let data: any = fetchData();

⚠️ But remember: overusing any defeats the purpose of TypeScript.
Use it only until you can define a proper type or interface.


🧰 Step 5: Add Type Definitions for External Libraries

If you use libraries like express, lodash, or react, you’ll need their type definitions.

You can install them using the DefinitelyTyped package repository:

npm install --save-dev @types/express
npm install --save-dev @types/react
npm install --save-dev @types/lodash

This helps TypeScript understand those libraries and provide autocomplete and error checking.


🚀 Step 6: Compile Your Code

Once you’ve renamed and fixed your first few files, try compiling your project:

npx tsc

If everything works, TypeScript will generate JavaScript files inside the folder defined by your tsconfig.json (often a dist/ or build/ folder).

You can run those just like before:

node dist/example.js

🔁 Step 7: Migrate Gradually, File by File

You don’t have to convert your whole project in one day.
You can mix .js and .ts files while you work through your codebase.

Here’s how to enable that flexibility:
In your tsconfig.json, make sure you have this line:

"allowJs": true

This tells TypeScript to accept .js files during the transition.
Once everything is converted, you can turn this off.


🧩 Step 8: Enable Strict Mode (When Ready)

TypeScript’s strict mode catches more errors — but it can be a bit strict (pun intended 😄).

If you’re just starting, you can leave it off.
Once your codebase stabilizes, turn it on for full safety.

"strict": true

✅ Example — Before and After

Before (JavaScript):

function calculateTotal(price, tax) {
  return price + tax;
}

console.log(calculateTotal("100", 20)); // Oops! JavaScript won't warn you.

After (TypeScript):

function calculateTotal(price: number, tax: number): number {
  return price + tax;
}

console.log(calculateTotal(100, 20)); // ✅ Type safe

Now, if you pass a string by mistake, TypeScript will catch it immediately.


🧭 Step 9: Use VS Code for a Better Experience

If you use Visual Studio Code, TypeScript support is built-in!
You’ll get:

  • Real-time error checking
  • Auto-completion
  • Quick fixes
  • Refactoring suggestions

Just open your project folder in VS Code — no extra setup needed.


💡 Tips for a Smooth Migration

  • Start with small utility files before touching large ones.
  • Add types gradually — don’t rush.
  • Use any temporarily, then replace it with real types.
  • Run tsc --noEmit to check for errors without generating files.
  • Keep your JavaScript tests running to confirm nothing breaks.

🧭 Summary

StepTaskPurpose
1Install TypeScriptSet up the compiler
2Rename .js → .tsEnable type checking
3Fix Type ErrorsImprove code safety
4Use any temporarilyTransition smoothly
5Add Type DefinitionsSupport libraries
6Compile and TestGenerate JS output
7Migrate GraduallyAvoid breaking changes
8Enable Strict ModeCatch more errors

🚀 Final Thoughts

Converting a JavaScript project into TypeScript doesn’t have to be scary.
You can take it one file at a time, get instant feedback from the compiler, and watch your code become safer, cleaner, and easier to maintain.

Start small, learn as you go — and soon, you’ll wonder how you ever coded without TypeScript.

Previous articleUnderstanding Type Inference and Type Assertion in TypeScript
Next articleWhat is HTML and How It Structures a Web Page
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here