Quick Revision of typescript

Quick Revision of typescript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It was created by Microsoft and offers optional static type checking, as well as many features from object-oriented and functional programming.

Here's a quick revision of TypeScript with an example:

  1. Variable Declarations: In TypeScript, you can declare variables using the let and const keywords, just like in JavaScript. However, TypeScript also supports type annotations that allow you to specify the type of a variable.

Example:

let myName: string = "John";
const myAge: number = 30;
  1. Functions: Functions in TypeScript can also have type annotations for parameters and return values. You can use arrow functions or the function keyword to declare functions.

Example:

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

const multiplyNumbers = (x: number, y: number): number => {
  return x * y;
};
  1. Interfaces: Interfaces in TypeScript are used to define the shape of an object. They can specify the types of properties, methods, and optional properties.

Example:

interface Person {
  name: string;
  age: number;
  job?: string;
  sayHello(): string;
}

const john: Person = {
  name: "John",
  age: 30,
  sayHello() {
    return `Hello, my name is ${this.name}`;
  },
};
  1. Classes: Classes in TypeScript allow you to use object-oriented programming concepts like inheritance, encapsulation, and abstraction. You can define properties, methods, and constructors with type annotations.

Example:

class Animal {
  protected name: string;
  constructor(name: string) {
    this.name = name;
  }
  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance}m.`);
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof! Woof!");
  }
}

const myDog = new Dog("Rover");
myDog.bark();
myDog.move(10);
  1. Generics: Generics in TypeScript allow you to write reusable code that works with a variety of types. You can define a generic type parameter that can be used in the function or class.

Example:

function reverse<T>(items: T[]): T[] {
  return items.reverse();
}

const numbers = [1, 2, 3, 4, 5];
const reversedNumbers = reverse(numbers);

const words = ["apple", "banana", "orange"];
const reversedWords = reverse(words);
  1. Enums: Enums in TypeScript allow you to define a set of named constants. You can use string or numeric enums, and you can also specify the starting value for numeric enums.

Example:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

const myDirection = Direction.Up;
  1. Union Types: Union types in TypeScript allow you to specify that a variable can have one of several possible types. You can use the | operator to combine types.

Example:

function printID(id: number | string) {
  console.log(`ID is ${id}`);
}

printID(123);
printID("abc");
  1. Type Assertions: Type assertions in TypeScript allow you to tell the compiler that you know more about the type of a value than it does. You can use the as keyword or angle brackets to assert the type of a value.

Example:

const myValue: any = "hello world";
const length: number = (myValue as string).length;
  1. Type Inference: Type inference in TypeScript allows you to omit type annotations in some cases, and the compiler will automatically infer the type of a value based on its usage. This can make code more concise and readable.

Example:

const myName = "John";
const myAge = 30;
const isMale = true;
  1. Type Aliases: Type aliases in TypeScript allow you to create a new name for a type. This can be useful for complex types that you want to reuse in multiple places.

Example:

type Point = {
  x: number;
  y: number;
};

function distance(p1: Point, p2: Point) {
  const dx = p2.x - p1.x;
  const dy = p2.y - p1.y;
  return Math.sqrt(dx * dx + dy * dy);
}

const p1: Point = { x: 0, y: 0 };
const p2: Point = { x: 1, y: 1 };
const d = distance(p1, p2);
  1. Intersection Types: Intersection types in TypeScript allow you to combine multiple types into a single type. You can use the & operator to combine types.

Example:

type Named = {
  name: string;
};

type Age = {
  age: number;
};

type Person = Named & Age;

const john: Person = {
  name: "John",
  age: 30,
};
  1. Type Guards: Type guards in TypeScript allow you to check the type of a value at runtime and perform different actions based on the result. You can use typeof, instanceof, or custom functions to create type guards.

Example:

function isNumber(value: any): value is number {
  return typeof value === "number";
}

function multiply(value: number | string, multiplier: number) {
  if (isNumber(value)) {
    return value * multiplier;
  } else {
    return NaN;
  }
}

const result = multiply(10, 2);
  1. Type Compatibility: TypeScript uses structural typing to determine type compatibility. This means that if two types have the same structure, they are considered compatible, even if they have different names.

Example:

type Point2D = {
  x: number;
  y: number;
};

type Point3D = {
  x: number;
  y: number;
  z: number;
};

function printPoint(point: Point2D) {
  console.log(`(${point.x}, ${point.y})`);
}

const point3D: Point3D = { x: 1, y: 2, z: 3 };
printPoint(point3D);
  1. Type Narrowing: Type narrowing in TypeScript allows you to narrow down the type of a value based on a runtime check. This can be useful when dealing with union types or unknown values.

Example:

function multiply(value: number | string, multiplier: number) {
  if (typeof value === "number") {
    return value * multiplier;
  } else {
    return NaN;
  }
}

const result = multiply(10, 2);
  1. Type Inference for Generics: Type inference for generics in TypeScript allows you to write code that is generic but also type-safe. When you call a generic function or create a generic class, TypeScript will infer the type based on the arguments you pass or the properties you define.

Example:

function identity<T>(value: T): T {
  return value;
}

const myNumber = identity(123);
const myString = identity("hello");
  1. Decorators: Decorators in TypeScript allow you to attach metadata to a class, method, or property at design time. You can use decorators to modify the behavior of a class or add additional functionality.

Example:

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

  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${key} with ${args}`);
    const result = originalMethod.apply(this, args);
    console.log(`Result is ${result}`);
    return result;
  };

  return descriptor;
}

class Calculator {
  @log
  add(a: number, b: number) {
    return a + b;
  }
}

const calculator = new Calculator();
const result = calculator.add(2, 3);
console.log(`Result is ${result}`);
  1. Type Parameters: Type parameters in TypeScript allow you to create generic functions or classes that can work with any type. You can use angle brackets to specify the type parameter.

Example:

function identity<T>(value: T): T {
  return value;
}

const myNumber = identity<number>(123);
const myString = identity<string>("hello");
  1. String Literal Types: String literal types in TypeScript allow you to specify a string as a type. This can be useful when working with enums or other situations where you want to restrict the values of a variable.

Example:

type Direction = "Up" | "Down" | "Left" | "Right";

function move(direction: Direction) {
  // ...
}

move("Up");
move("Left");
  1. Index Signatures: Index signatures in TypeScript allow you to define the types of dynamic properties on an object. You can use square brackets to specify the name of the property and the type of its value.

Example:

type Dictionary<T> = {
  [key: string]: T;
};

const myDictionary: Dictionary<number> = {
  one: 1,
  two: 2,
  three: 3,
};
  1. Async/Await: TypeScript has built-in support for async/await, which allows you to write asynchronous code that looks and behaves like synchronous code. You can use the async keyword to mark a function as asynchronous and the await keyword to pause execution until a Promise is resolved.

Example:

async function getData() {
  const response = await fetch("https://example.com/data");
  const data = await response.json();
  return data;
}

getData().then((data) => {
  console.log(data);
});
  1. Optional Chaining: Optional chaining in TypeScript allows you to access properties and methods on an object without worrying about whether they exist or not. If a property or method does not exist, the expression evaluates to undefined instead of throwing an error.

Example:

const user = {
  name: "John Doe",
  address: {
    street: "123 Main St",
    city: "Anytown",
  },
};

const city = user.address?.city;
console.log(city); // "Anytown"

const zip = user.address?.zip;
console.log(zip); // undefined
  1. Nullish Coalescing: Nullish coalescing in TypeScript allows you to provide a default value for a variable if it is null or undefined. This is similar to the || operator, but with the added benefit of not treating falsy values like 0 or an empty string as nullish.

Example:

const name = null ?? "Unknown";
console.log(name); // "Unknown"

const age = 0 ?? 18;
console.log(age); // 0
  1. Namespace: Namespaces in TypeScript allow you to organize your code into logical groups and prevent naming conflicts. You can use the namespace keyword to create a new namespace.

Example:

namespace MyNamespace {
  export function greet(name: string) {
    console.log(`Hello, ${name}!`);
  }
}

MyNames

Did you find this article valuable?

Support Sawan Kumar Jha by becoming a sponsor. Any amount is appreciated!