All About TypeScript  | Big Brother of JavaScript

All About TypeScript | Big Brother of JavaScript

Introduction to TypeScript

TypeScript is a superset of JavaScript.

TypeScript builds on top of JavaScript. First, you write the TypeScript code. Then, you compile the TypeScript code into plain JavaScript code using a TypeScript compiler.

TypeScript files use the .ts extension rather than the .js extension of JavaScript files.

Why use TypeScript

There are two main reasons to use TypeScript:

  1. TypeScript adds a type system to help you avoid many problems with dynamic types in JavaScript.
  2. TypeScript implements the future features of JavaScript a.k.a ES Next so that you can use them today.

Mainly TypeScript improves your productivity while helping avoid bugs.

Lets Start Example with All Types:

Variable

let variableName: type = Value;

let userName: string = "Munna";
let age: number = 23;
let isProgrammer: boolean = true;
const PI: number = 3.1416;
let bigNum: bigint = 34352345352342352345n;

Array Type

let number: number[] = [3, 4, 5, 23, 2, 3];

Object Type

let obj: { user: string; age: number } = { user: "Munna", age: 23 };

function Type

function add(a: number, b: number): number {
  return a + b;
}

Arrow function Type System

const add2 = (a: number, b: number): number => {
  return a + b;
};

Tuple like Array

const student: [string, number] = ["munna", 23];

Enum Type enum version { ver1, ver2, } Any Type

let result: any;
result = 10.123;

Function Type Details

const printArray = (num: number[]): void => {
  for (let index = 0; index < num.length; index++) {
    const element = num[index];

    console.log(element);
  }
};
const num: number[] = [3, 4, 2, 33, 42, 34];
printArray(num);

Function Return type

const stringLength = (a: string): number => {
  return a.length;
};
console.log(stringLength("Hello"));

Function optional Parameters Type

Stracture: ?: typeName

function multiply(a: number, b: number, c?: number): number {
  if (typeof c !== "undefined") {
    return a * b * c;
  }
  return a * b;
}

Function Default Parameters

function applyDiscount(price: number, discount: number = 0.05): number {
  return price * (1 - discount);
}
console.log(applyDiscount(100));

Rest Parameters Type ...something: typename || Maximum array

function getTotal(...numbers: number[]): number {
  let total = 0;
  numbers.forEach((num) => (total += num));
  return total;
}

function Overloading same function Name Different type as a parameter.

function add3(a: number, b: number): number;
function add3(a: string, b: string): string;
function add3(a: any, b: any): any {
  return a + b;
}

writer: morshedulmunna Email: