Introduction to TypeScript

What is TypeScript?

TypeScript is a superset of JavaScript, which means it builds on JavaScript by adding new features and advantages. It's designed to help developers write better and more maintainable code. However, browsers can't execute TypeScript directly, so it needs to be compiled into JavaScript first.

Key Points:

  • Superset of JavaScript: Adds new features to JavaScript.

  • Compilation: TypeScript is compiled to JavaScript before execution.

  • Error Handling: Possible errors are detected during compilation, not at runtime.

Why Use TypeScript?

Example Problem in JavaScript:

function add(num1, num2) {
  return num1 + num2;
}

console.log(add('2', '3')); // Output: 23

In JavaScript, this code runs without any errors, but the result might not be what you expect. Instead of adding the numbers, it concatenates them as strings, giving you "23".

Mitigation Strategies in JavaScript:

You could add checks to validate and sanitize user input:

function add(num1, num2) {
  if (typeof num1 === 'number' && typeof num2 === 'number') {
    return num1 + num2;
  } else {
    throw new Error('Invalid input');
  }
}

Even with these checks, developers can still write invalid code, and it can be challenging to catch all errors.

How TypeScript Helps:

TypeScript helps developers write better code by providing a type system. It checks for type errors during the compilation process, making the code more predictable and reducing runtime errors.

Getting Started with TypeScript

Installation:

To install TypeScript, use the following npm command:

npm install -g typescript

This installs TypeScript globally on your system, making the tsc (TypeScript Compiler) command available in your terminal.

Writing Your First TypeScript Code:

  1. Create a TypeScript file: Save the following code in a file named helloworld.ts.
function add(num1: number, num2: number): number {
  return num1 + num2;
}

console.log(add(2, 3)); // Output: 5
  1. Compile the TypeScript file: Use the TypeScript Compiler (tsc) to compile helloworld.ts into JavaScript.
tsc helloworld.ts
  1. Run the compiled JavaScript file: This generates a helloworld.js file, which you can run using Node.js or include in your HTML file.
node helloworld.js

Advantages of TypeScript:

  • Early Error Detection: Catches errors at compile time rather than at runtime.

  • Improved Readability and Maintainability: Type annotations make the code easier to understand.

  • Enhanced Tooling: Better code completion and refactoring tools in editors like Visual Studio Code.