typescript basics

Typescript is a language developed by Microsoft and it is a superset of JS. Main objective of typescript is to provide type safety to JS code.

npm install typescript -D
npx tsc

#Below command will create tsconfig.json file where you can put config for 
# typescript compiler
npx tsc --init          

  let name: string = "Sagar";   
  let id:number = 1234
  
  //below statement will throw error saying 
  //type number is not assignable to type string
  name = 23

  //Arrays
  let users: string[] = [];
  users.push("Sagar"); 

  //tuples - it's an array with mixed types
  let car: [number, string, boolean];

  // store values in tuple
  car = [30000, "Tesla", true];



  //enums - by default it will start from 0
  enum ShirtSize{
    Small,
    Medium,
    Large
  }

  //we can also assign the numbers to enums like below
  enum HTTPCodes{
    Success : 200,
    Error : 400
  }

  //we can also assign the names to enums like below
  enum Days{
    SUN : 'Sunday',
    MON : 'Monday'
  }

  //adding types to objects...please note that color is optinal prop
  let phone:{price:number,model:string, color?:string} = {
    price : 800,
    model : 'samsung'
  }

  //above syntax is works but not recommended. Instead of that,
  // use type alias or interfaces

 type Phone = {
  price : number,
  model: string | number,
  color?: string
 }

 let phone1:Phone = {
  price : 1300,
  model : "iPhone 14",
  color: "golden"
 } 

 console.log(phone1)

 //using interface
 
 interface IPhone  {
  price : number,
  model: string,
  color?: string
 }

 let phone2:IPhone = {
  price : 1300,
  model : "iPhone 14",
  color: "golden"
 } 

 console.log(phone2)


 //typing functions
 function sum(a: number, b: number, ...others: number[]) : number {
  return a + b + others.reduce((x, y) => x + y, 0);
}

//using type alias - note that => is added before return type
type sumType = (a: number, b: number) => number;

//using interface - note that : is added before return type
interface sumType {
  (a: number, b: number) : number;
}

//casting can be done in ways - obj as or  (<MyType>obj)

Web development and Automation testing

solutions delivered!!