Learn TypeScript — The Ultimate Beginners Guide : Built-in Types

by:

Softwares


TypeScript Fundamentals in One Place

1. Introduction

Programming language divide into two categories :

  • Statically typed
  • Dynamically typed

in Statically-typed languages (C, Java, C#, … ), the type of variable is set at the compile-time and cannot change later.

in Dynamically-typed languages (PHP, JavaScript, Python, … ), the type of variable is determined at the run-time and can change later.

TypeScript is a programming language build on top of JavaScript ( essentially JavaScript with static typing and some additional features ) , so before we star make sure that you are familiar with this concepts in javascript:

  • Variables
  • Arrays
  • Objects
  • Functions
  • Arrow Functions
  • Destructuring

2. Built-in Types

as we know JavaScript has built-in types like :

  • number
  • string
  • boolean
  • array
  • object
  • undefined
  • null

So TypeScript extend this list and introduce some new built-in types such as :

  • any
  • unknown
  • never
  • enum
  • tuple

1- The Any Type : when you declare a variable and don’t initialize it , the typescript compiler will assume that variable is type of any which means you can assign any type of data into it , here is an example :

let anyType; // let anyType: any

anyType = 12;

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

anyType = "Random string";

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

Exit fullscreen mode

Note : To declare variables, functions you just need to follow this syntax :

let numberType: number = 12;
let numberType: string = 12;

function taxe(income: number): number 
  return income * 0.2;

Enter fullscreen mode

Exit fullscreen mode

2- Arrays :

let numbers = [1, 2, 3]; // let numbers: number[] = [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 length and types for each index.

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

Exit fullscreen mode

4- Enums :

// const small = 1;
// const medium = 1;
// const large = 1;

const enum Size 
  Small = 1,
  medium,
  large,


let mySize: Size = Size.Small;

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

Exit fullscreen mode

4- Objects :

/*
let employee: 
  id:number,
  name:string
 = 
  id:1,
  name:'zineddine'

*/

let employee = 
  id: 1,
  name: "zineddine",
;

let user: 
  readonly id: number;
  name: string;
  pseudo?: string;
  retire: (date: Date) => void; // function declaration
 = 
  id: 1,
  name: "zineddine",
  retire: (date: Date) => 
    console.log(date);
  ,
;

user.id = 10; // Cannot assign to 'id' because it is a read-only property
Enter fullscreen mode

Exit fullscreen mode

5- Type Aliases :

type User = 
  readonly id: number;
  name: string;
  pseudo?: string;
  retire: (date: Date) => void; // function declaration
;

let user: User = 
  id: 1,
  name: "zineddine",
  retire: (date: Date) => 
    console.log(date);
  ,
;
Enter fullscreen mode

Exit fullscreen mode

6- Union Types :

function kgToLbs(kg: number | string): number 
  // Narrowing
  if (typeof kg === "string") 
    return parseFloat(kg) * 2.2046;
  

  return kg * 2.2046;

Enter fullscreen mode

Exit fullscreen mode

7- Intersection Types :

// make no sense right ?
let weight: number & string;

// let see a realistic example

type draggable = 
  drag: () => void;
;

type resizable = 
  resize: () => void;
;

let UIWidget: draggable & resizable;

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

Exit fullscreen mode

8- Literal Types :

// let quantity: 5 | 100;

type Quantity = 50 | 100;
let quantity: Quantity;

quantity = 5; // Type '5' is not assignable to type 'Quantity'

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

Exit fullscreen mode

9- Nullable Types :

function greeting(name: string | null | undefined) 
  if (name) 
    return `Hello, $name`;
  
  return "Hello, World";


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

Exit fullscreen mode

10- Optional Chaining :

type User = 
  id: number;
  birthday?: Date;
;

function getUser(id: number): User | 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 

// optional property access operator
getUser(1)?.birthday?.getFullYear(); // output 2000

// optional element access operator

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

// optional function call operator

let log: any = null;

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

Exit fullscreen mode

11- Nullish Coalescing Operator :

let speed: number | null = null;

let ride = ;
Enter fullscreen mode

Exit fullscreen mode

12- Type Assertions :

let phone = document.getElementById("phone");

phone.value; // Property 'value' does not exist on type 'HTMLElement'

// let email = <HTMLInputElement> document.getElementById('email');

let email = document.getElementById("email") as HTMLInputElement;

email.value;
Enter fullscreen mode

Exit fullscreen mode

13- The Unknown Type :

function render(document: any) 
  // no compile error , but runtime error
  document.whatEver();


function render(document: unknown) 
  /*
  compile error, now the compîler forces us to check the type of the argument before using it

  */

  document.whatEver();

  if (document instanceof String) 
    document.toLocaleLowerCase();
  

Enter fullscreen mode

Exit fullscreen mode

13- The Never Type :

function reject(message: string): never 
  throw new Error(message);


function processEvent(): never 
  while (true) 
    // ...
  


processEvent();

/*

 => this code will never be executed , but the compiler don't tell us , so we have to use the `never` type.

 => now the compiler will tell us that the function will never return : Unreachable code detected.

 */

console.log("Hello World!");


Enter fullscreen mode

Exit fullscreen mode

That’s it for the first chapter !

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





Source link

Leave a Reply

Your email address will not be published.