0
0
Typescriptprogramming~5 mins

Migrating JavaScript to TypeScript

Choose your learning style9 modes available
Introduction

TypeScript helps catch errors early by adding types to JavaScript. Migrating makes your code safer and easier to understand.

You want to find bugs before running your code.
You want better code suggestions in your editor.
You want to work on a large project with many developers.
You want to use modern JavaScript features with type safety.
You want to improve code readability and maintenance.
Syntax
Typescript
Change file extension from .js to .ts
Add type annotations like:
function greet(name: string): string {
  return `Hello, ${name}!`;
}

TypeScript files use the .ts extension instead of .js.

Adding types like string or number helps the compiler check your code.

Examples
This function adds two numbers and tells TypeScript the inputs and output are numbers.
Typescript
function add(a: number, b: number): number {
  return a + b;
}
Here, we tell TypeScript that message must always be a string.
Typescript
let message: string = 'Hello!';
This declares an array of numbers, so TypeScript knows what type of items it holds.
Typescript
const numbers: number[] = [1, 2, 3];
Sample Program

This program greets a user by name. TypeScript checks that name is a string.

Typescript
function greet(name: string): string {
  return `Hello, ${name}!`;
}

const userName = 'Alice';
console.log(greet(userName));
OutputSuccess
Important Notes

Start by renaming your .js files to .ts.

Add types gradually; you don't need to type everything at once.

Use any type temporarily if you are unsure, but try to replace it later.

Summary

TypeScript adds types to JavaScript for safer code.

Rename files to .ts and add type annotations step-by-step.

This helps catch errors early and improves code clarity.