TypeScript 101

TypeScript 101
Photo by Kyle Head / Unsplash

TypeScript is a superset of JavaScript that adds optional type annotations and other features to the language. It was developed and is maintained by Microsoft and is used to build large scale, complex JavaScript applications.

TypeScript provides optional type annotations, which allow developers to specify the types of variables, function parameters and return values. This helps to catch type-related errors early in the development process, rather than at runtime. TypeScript also includes features such as class and interface definitions, modules, and decorators, which can be used to write more robust and maintainable code.

TypeScript also provides support for advanced features such as async/await, destructuring, spread operators, etc. TypeScript also provides built-in support for JSX, the syntax extension used by React.

TypeScript is transpiled to JavaScript, so the code written in TypeScript can run on any JavaScript environment. This allows developers to use TypeScript's features and benefits, while still being able to run the code on any platform that supports JavaScript.

TypeScript is widely used in the industry, many companies such as Asana, Airbnb, Asos, AWS, etc use TypeScript for their web application development. It's also supported by many popular frameworks and libraries such as Angular, React, Vue.js, Nest.js, Express.js, etc.

Here are a few examples of how TypeScript can be used to write more robust and maintainable code:

Type annotations: TypeScript allows you to specify the types of variables, function parameters, and return values using type annotations. This helps to catch type-related errors early in the development process, rather than at runtime. For example:

let myString: string = 'hello world';
let myNumber: number = 42;

function add(x: number, y: number): number {
  return x + y;
}

Classes and interfaces: TypeScript supports classes and interfaces, which can be used to define custom types and encapsulate related data and behavior. For example:

class Point {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

  distanceFromOrigin(): number {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
}

Modules: TypeScript supports the use of modules to organize and reuse code. This allows you to split your application into smaller, more manageable pieces. For example:

export class Point {
    // ...
}

export function distance(p1: Point, p2: Point): number {
    // ...
}

Decorators: TypeScript supports decorators, which are a way to add meta-data to a class, method, or property. Decorators can be used to add functionality, such as logging or validation, without modifying the original code. For example:

function logMethod(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;

  descriptor.value = function(...