DEV Community

Cover image for Transitioning from JavaScript to TypeScript: My experience and thoughts
William Zeng
William Zeng

Posted on

Transitioning from JavaScript to TypeScript: My experience and thoughts

When I first started learning JavaScript, I was amazed by its power and flexibility. I could write small scripts, build interactive websites, and eventually tackle more complex web applications. However, as my projects grew in size and complexity, around this time I heard more about TypeScript and how it could help improve code quality and maintainability - especially when it came to debugging and managing large codebases.

During my fellowship, we were tasked with learning a new language on our own, choosing one we would use to build our capstone project - a culmination of everything we had learned. I decided to go with TypeScript, often called a superset of JavaScript because the language includes all the features of JavaScript while adding powerful tools like static typing, interfaces, and enhanced developer support. These additions, which I will detail later in this blog, make code easier to write, debug, and maintain - especially in larger or more complex projects.

Switching to TypeScript: How Its Features Ease the Transition

1. Smarter Tools and Code Suggestions

TypeScript uses “types” to understand the kind of data you are working with. This allows for:

Better Autocompletion: Your IDE (e.g., VS Code, WebStorm) understands the methods and properties available for variables, saving time and reducing mistakes.

For example, when working with a string, the editor will suggest string-specific methods, such as .toUpperCase(), .slice(), or .substring(). Similarly, for an array, it might suggest .map(), .filter(), or .push().

Early Error Detection: TypeScript checks your code as you write it, known as compile-time checking. If you try to use a string where a number is expected, TypeScript will warn you before you run the program.

Easier Navigation: Knowing types means your editor can link directly to where a variable, function, or object is defined, helping you quickly understand how your code fits together.

2. Catch Bugs Early

With JavaScript, some bugs may only become apparent when the program is running, also known as runtime, which can be time-consuming to debug. TypeScript, on the other hand:

Finds Bugs During Development: TypeScript provides warnings when there are type mismatches, such as attempting to use a number where a string is expected, helping you catch potential logical issues before runtime.

Prevents Simple Mistakes: TypeScript catches issues like misspelled variable names or incorrect function arguments before they cause problems.
This saves time and allows for bugs to be fixed before reaching production.

3. Easier Code Maintenance

TypeScript makes it easier to read, refactor, and update your code by making everything more predictable.

Clear Data Flow: Types show exactly what kind of data each part of your code expects and returns. This clarity is invaluable when working on a team or revisiting old projects. As codebases grow, TypeScript’s type annotations make it easier to maintain and refactor code. Types help you understand how different parts of the application interact, making it more manageable in the long run.

Safer Changes: If you change how a function works, TypeScript will alert you to all the places in your code that might be affected, so you do not accidentally break things

Faster Debugging: Because TypeScript catches issues during development, you spend less time chasing bugs and more time building features.

4. Perfect for Large Projects

As projects grow, managing JavaScript can get messy. TypeScript shines in these situations:

Handles Complexity: By enforcing consistent data structures and types, TypeScript keeps your code organized and scalable.

Improves Teamwork: Types make it easier for team members to understand each other’s code, reducing misunderstandings and speeding up development.

The Gist: Key TypeScript Features

Static Typing: Lets you define what type of data (like string, number, or object) a variable should hold.

Interfaces: Define how objects should look, making your code more predictable and easier to understand.

Enhanced Tooling: Tools like VS Code work seamlessly with TypeScript, giving you real-time feedback and smart navigation options.

Forward and Backward Compatibility with JavaScript

TypeScript supports the latest JavaScript features, so you can write modern code that stays up-to-date with new standards. It also ensures backward compatibility by converting your code into older JavaScript versions, making it work on legacy systems.

For example, you can use modern features like async/await in TypeScript, and it will automatically convert your code to work on older browsers that do not support it. This way, you get the best of both worlds: using new features while ensuring broad compatibility.

Differences Between JavaScript and TypeScript

Type Annotations:

In JavaScript, variables are dynamically typed, which means their type can change at runtime. This flexibility can sometimes introduce hard-to-track bugs.

Javascript Example
let message = "Hello, world!";
message = 77;  // No error, but can cause issues later
message = true; // Also works, but may cause bugs
Enter fullscreen mode Exit fullscreen mode

TypeScript fixes this by allowing you to declare the type of a variable explicitly. If you try to assign a value of a different type, TypeScript will throw an error at compile-time.

Typescript Example

let message: string = "Hello, world!";
// message = 77;  // Error: Type 'number' is not assignable to type 'string'
// message = true; // Error: Type 'boolean' is not assignable to type 'string'
Enter fullscreen mode Exit fullscreen mode

This prevents accidental type changes that could lead to bugs in large, complex codebases.

Function Type Checking

In JavaScript, functions are loosely typed. You can pass any type of argument to a function, and JavaScript will not complain - even if it does not make sense logically.

Javascript Example

function greet(name) {
  return `Hello, ${name}`;
}
greet("Alice");  // Works fine
greet(42);       // Also works, but it's not intended
Enter fullscreen mode Exit fullscreen mode

TypeScript allows you to explicitly define what types are expected for function arguments, ensuring that only the correct type is passed.

Typescript Example

function greet(name: string): string {
  return `Hello, ${name}`;
}
greet("Alice");  // Works fine
// greet(42);     // Error: Argument of type 'number' is not assignable to parameter of type 'string'
Enter fullscreen mode Exit fullscreen mode

This ensures that your functions behave as expected and reduces potential bugs at runtime.

Interfaces for Object Structures

JavaScript allows you to define objects with flexible structures, but this flexibility can lead to unpredictable bugs if object properties are modified incorrectly.

Javascript Example 

let person = { name: "John", age: 30 };
person.age = "thirty";  // No error, but could cause issues later
Enter fullscreen mode Exit fullscreen mode

TypeScript introduces interfaces, which let you define specific structures for objects. This ensures that objects adhere to a set pattern and prevents errors like assigning the wrong data types to object properties.

Typescript Example

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

let person: Person = { name: "John", age: 30 };
// person.age = "thirty";  // Error: Type 'string' is not assignable to type 'number'
Enter fullscreen mode Exit fullscreen mode

This helps prevent common bugs that stem from improperly structured data.

Classes and Inheritance

TypeScript extends JavaScript’s class-based structure with type safety for class properties and methods, providing more clarity and predictability.

Javascript Example

class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hello, my name is ${this.name}!`);
  }
}
Enter fullscreen mode Exit fullscreen mode

In TypeScript, you can define the types of properties and method return values, making the class more predictable and less error-prone.

Typescript Example

class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet(): {
    console.log(`Hello, my name is ${this.name}!`);
  }
}
Enter fullscreen mode Exit fullscreen mode

This added type clarity in classes helps in managing larger projects where inheritance and object-oriented principles are used.

Some Personal Insights

Gradual Adoption vs. Starting Fresh

The approach you choose depends on your project and personal goals. If you are working on a small project or a simple script, TypeScript’s gradual adoption model might make sense. Since TypeScript is a superset of JavaScript, this allows you to introduce it step-by-step, helping you spot potential issues without needing to refactor everything at once.

For larger projects or those aiming for long-term scalability, starting fresh with a new TypeScript project is often the best option. This allows you to fully embrace TypeScript's benefits from the start, including static typing and improved code organization. By starting new, you avoid the complications of integrating TypeScript into an existing codebase and can apply best practices from the outset, ensuring your code is cleaner, more maintainable, and less error-prone.

Enable Strict Mode

To get the most out of TypeScript, enable strict mode in your
tsconfig.json file. This ensures all strict type-checking features are turned on, making your code more robust and catching more potential errors.

JSON

{
  "compilerOptions": {
    "strict": true
  }
}
Enter fullscreen mode Exit fullscreen mode

Understanding the any Type in TypeScript:

The any type allows you to bypass TypeScript’s strict typing for specific variables or functions temporarily. Think of it as returning to JavaScript mode - where variables can hold any type of value without restriction.

Typescript Example

let message: any = "Hello, World!"; // 'value' can hold any type of data 
message = 42; // Now 'value' holds a number 
message = true; // Now 'value' holds a boolean
Enter fullscreen mode Exit fullscreen mode

While this can help you ease into the language, relying too much on any can undermine TypeScript’s core benefit: type safety. It's better to start using more specific types as soon as possible. This will help you get the most out of TypeScript’s type checking, avoid becoming reliant on any, and ensure a smoother learning experience with fewer refactors later on.

Conclusion:

TypeScript is a powerful tool for developers familiar with JavaScript, offering significant advantages in type safety, tooling, and maintainability. By improving code predictability and reducing bugs, TypeScript is an excellent choice for those looking to elevate their JavaScript skills. It integrates seamlessly into existing JavaScript projects, and its gradual learning curve ensures a smooth transition for developers at any level.

Since transitioning to a TypeScript environment, I’ve grown accustomed to its built-in error-catching features, often taking them for granted as part of the development process. It was not until I reflected on my earlier experiences with JavaScript that I realized how much I now rely on TypeScript’s type-checking capabilities.

That said, I owe a lot to JavaScript. It was the language I first used to dive into web development, and it gave me hands-on experience in building simple applications. My early days with JavaScript, especially when working on projects like single-fetch tasks, were key in shaping my growth as a developer. It remains my go-to for smaller, flexible projects where its simplicity still shines.

Thank you, JavaScript - Hello, TypeScript!

Resources that supported me along the way

Check out this blog for a deeper dive and guide on setting up TypeScript

Top comments (0)