Saturday, June 18, 2022
HomeWordPress DevelopmentBe taught TypeScript — The Final Learners Information : Constructed-in Sorts

Be taught TypeScript — The Final Learners Information : Constructed-in Sorts


TypeScript Fundamentals in One Place

Follow me



1. Introduction

Programming language divide into two classes :

  • Statically typed
  • Dynamically typed

in Statically-typed languages (C, Java, C#, … ), the kind of variable is about on the compile-time and can’t change later.

in Dynamically-typed languages (PHP, JavaScript, Python, … ), the kind of variable is set on the run-time and may change later.

TypeScript is a programming language construct on high of JavaScript ( primarily JavaScript with static typing and a few extra options ) , so earlier than we star just be sure you are conversant in this ideas in javascript:

  • Variables
  • Arrays
  • Objects
  • Features
  • Arrow Features
  • Destructuring



2. Constructed-in Sorts

as we all know JavaScript has built-in sorts like :

  • quantity
  • string
  • boolean
  • array
  • object
  • undefined
  • null

So TypeScript prolong this record and introduce some new built-in sorts equivalent to :

  • any
  • unknown
  • by no means
  • enum
  • tuple

1- The Any Kind : once you declare a variable and do not initialize it , the typescript compiler will assume that variable is kind of any which implies you possibly can assign any kind of information into it , right here is an instance :

let anyType; // let anyType: any

anyType = 12;

console.log(typeof anyType); // output: quantity

anyType = "Random string";

console.log(typeof anyType); // output: string
Enter fullscreen mode

Exit fullscreen mode

Be aware : To declare variables, capabilities you simply must observe this syntax :

let numberType: quantity = 12;
let numberType: string = 12;

operate taxe(revenue: quantity): quantity {
  return revenue * 0.2;
}
Enter fullscreen mode

Exit fullscreen mode

2- Arrays :

let numbers = [1, 2, 3]; // let numbers: quantity[] = [1, 2, 3]

let anyTypes = []; // let anyTypes: any[]

anyType[0] = 100;
anyType[0] = "r_string";

let names = ["ahmed", "zineddine"]; // let names: string[] = ["ahmed", "zineddine"]
Enter fullscreen mode

Exit fullscreen mode

3- Tuples : A tuple is a typed array with a pre-defined size and kinds for every index.

let worker: [number, string] = [1, "Steve"];
Enter fullscreen mode

Exit fullscreen mode

4- Enums :

// const small = 1;
// const medium = 1;
// const massive = 1;

const enum Dimension {
  Small = 1,
  medium,
  massive,
}

let mySize: Dimension = Dimension.Small;

console.log(mySize); // output : 1
Enter fullscreen mode

Exit fullscreen mode

4- Objects :

/*
let worker: {
  id:quantity,
  title:string
} = {
  id:1,
  title:'zineddine'
}
*/

let worker = {
  id: 1,
  title: "zineddine",
};

let person: {
  readonly id: quantity;
  title: string;
  pseudo?: string;
  retire: (date: Date) => void; // operate declaration
} = {
  id: 1,
  title: "zineddine",
  retire: (date: Date) => {
    console.log(date);
  },
};

person.id = 10; // Can't assign to 'id' as a result of it's a read-only property
Enter fullscreen mode

Exit fullscreen mode

5- Kind Aliases :

kind Person = {
  readonly id: quantity;
  title: string;
  pseudo?: string;
  retire: (date: Date) => void; // operate declaration
};

let person: Person = {
  id: 1,
  title: "zineddine",
  retire: (date: Date) => {
    console.log(date);
  },
};
Enter fullscreen mode

Exit fullscreen mode

6- Union Sorts :

operate kgToLbs(kg: quantity | string): quantity {
  // Narrowing
  if (typeof kg === "string") {
    return parseFloat(kg) * 2.2046;
  }

  return kg * 2.2046;
}
Enter fullscreen mode

Exit fullscreen mode

7- Intersection Sorts :

// make no sense proper ?
let weight: quantity & string;

// let see a sensible instance

kind draggable = {
  drag: () => void;
};

kind resizable = {
  resize: () => void;
};

let UIWidget: draggable & resizable;

UIWidget = {
  drag: () => {},
  resize: () => {},
};
Enter fullscreen mode

Exit fullscreen mode

8- Literal Sorts :

// let amount: 5 | 100;

kind Amount = 50 | 100;
let amount: Amount;

amount = 5; // Kind '5' is just not assignable to kind 'Amount'

kind Metric = "m" | "cm" | "mm";
Enter fullscreen mode

Exit fullscreen mode

9- Nullable Sorts :

operate greeting(title: string | null | undefined) {
  if (title) {
    return `Hi there, ${title}`;
  }
  return "Hi there, World";
}

greeting("John");
greeting(null);
greeting(undefined);
Enter fullscreen mode

Exit fullscreen mode

10- Elective Chaining :

kind Person = {
  id: quantity;
  birthday?: Date;
};

operate getUser(id: quantity): Person | null | undefined {
  if (id === 1) {
    return {
      id,
      birthday: new Date("2000-01-01"),
    };
  }

  return null;
}

getUser(0); // output null

getUser(1); // output { id: 1, birthday: Date }

// non-compulsory property entry operator
getUser(1)?.birthday?.getFullYear(); // output 2000

// non-compulsory component entry operator

let workers: string[] | null = null;
workers?.[0];

// non-compulsory operate name operator

let log: any = null;

log?.("hey"); // return undefined
Enter fullscreen mode

Exit fullscreen mode

11- Nullish Coalescing Operator :

let velocity: quantity | null = null;

let journey = ;
Enter fullscreen mode

Exit fullscreen mode

12- Kind Assertions :

let cellphone = doc.getElementById("cellphone");

cellphone.worth; // Property 'worth' doesn't exist on kind 'HTMLElement'

// let e mail = <HTMLInputElement> doc.getElementById('e mail');

let e mail = doc.getElementById("e mail") as HTMLInputElement;

e mail.worth;
Enter fullscreen mode

Exit fullscreen mode

13- The Unknown Kind :

operate render(doc: any) {
  // no compile error , however runtime error
  doc.whatEver();
}

operate render(doc: unknown) {
  /*
  compile error, now the compîler forces us to examine the kind of the argument earlier than utilizing it

  */

  doc.whatEver();

  if (doc instanceof String) {
    doc.toLocaleLowerCase();
  }
}
Enter fullscreen mode

Exit fullscreen mode

13- The By no means Kind :

operate reject(message: string): by no means {
  throw new Error(message);
}

operate processEvent(): by no means {
  whereas (true) {
    // ...
  }
}

processEvent();

/*

 => this code won't ever be executed , however the compiler do not inform us , so we've to make use of the `by no means` kind.

 => now the compiler will inform us that the operate won't ever return : Unreachable code detected.

 */

console.log("Hi there World!");


Enter fullscreen mode

Exit fullscreen mode

That’s it for the primary chapter !

Github hyperlink : TypeScript-Fundamentals-in-One-Place



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments