TypeScript(JS)

What is TypeScript ?
TypeScript is a superset set of javascript which is free and open-source high-level programming language developed by Microsoft that adds static typing with optional type annotations to JavaScript. It is designed for the development of large applications and transpiles to JavaScript. It is strong static characters to check data type in typescript, This allows us to find any possible errors at compile time rather than run time.

Data Types in TypeScript

Data Types in JavaScript
  • string Type
  • number Type
  • boolean Type
  • null Type
  • undefined Type
  • object Type
  • bigInt Type
  • symbol Type
  • unknow Type
  • never Type
  • symbol Type
  • Array - T[]
  • Tuples- [T,T]
  • Unions (t: T)

String Type

                  
                    let x: string = 'Satendr Chauhan';
                    function show(val: string) {
                      console.log(val);
                    }
                    show(x);
                  
                

Number Type

                  
                    let x: number = 30;
                    function show(val: numbre) {
                      console.log(val);
                    }
                    show(x)
                  
                

Boolean Type

                  
                    //Boolean type
                      let b: boolean = true;
                      function showBool(val: boolean) {
                        console.log(val);
                      }
                      showBool(b);
                  
                

Function

                  
                  // Function
                    function getTime(): number {
                      return new Date().getTime();
                    }

                    function showSome(): object | string | number {
                      const obj = {
                        name: 'saten',
                      };
                      return obj;
                      //return  'chauhan';
                      //return 45;
                    }
                    console.log(showSome());
                  
                

Void Type

Void is to represents the absence of a value, typically It is used for functions that do not return a value
                  
                    function showMsg(msg: string): void {
                      console.log(msg);
                    }
                    showMsg('This saten Pratap')
                  
                

Array Type

                  
                    let arr: string[] = ['php', 'java', 'React', 'Javascript']; // String array type
                    let array: [string, number, boolean] = ['saten', 45, true]; // Specific value in array type
                    let arry: any[] = ['saten', 45, true]; // Array type but value can be anything string, number, boolean etc.
                    
                   // Using sqaure brackets to creat array
                    const nums: number[] = [13, 4, 8, 2, 6, 10, 12]; //Type inference, number array type

                    const data: number[] = [4, 5, 6, 7, 8, 2, 3, 1];

                    //Using array constructor to create array
                    const arr: number[] = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);

                    //Using the Array.of method to create array
                    // const names: string[] = Array.of('Ram', 'Sham', 'Naman', 'Tapan');

                    // Array with multiple data types
                    const arrData: (string | number | boolean)[] = [
                      'saten',
                      36,
                      'kanpur',
                      true,
                      'up',
                      20,
                    ];

                    console.log(arrData);
                  
                

Unknow Type

Unknow is similar to any but safer alternative to any.
Unkown type will be present from being used.
Unknown is best used when we do not know the type of data being type to add later a type.
                  
                    let data:unkow = 12;
                    data="Satendr"  // string given
                    // Casting is override a type  using as
                    let city: unknown = 'Mumbai';
                    console.log((city as string).length);
                  
                

Never Type

Never is rarely used especially by itsself.
Never type indicate the value that will never return or occur.
A function which will not return to its end point or always throw a exception.
Never can not be null.
                  
                    function showError(errorMsg:string):never {
                      throw new Error(errorMsg);
                    }
                  
                

Any Type

Any type is allow us to accept any type of data, It does not check data type, it accept any type
                  
                    let a: any = 'Saten Chauhan';
                    let arry: any[] = ['saten', 45, true];
                  
                

BigInt Type

BigInt literal by adding an n to the end of any integer numeric literal
                  
                  /* BigInt */
                    let bigintNum = Number.MAX_SAFE_INTEGER;
                    let num1: bigint = 9007199254740991n;
                    let num2 = BigInt('9007199254740991');
                    console.log(num2);
                  
                

Alias Type

Alias a type is a way to give a name to a specific type or combination of types.
It allows us to create a custom name for a type and making ti wasier to reuse in different partsof our code.
                  
                    interface RecObj {
                      height: number,
                      width: number
                    }

                    const rectangle: RecObj = {
                        height: 40,
                        width: 20
                    };
                  
                

Unions Type

Union types are a way of declaring a type that could be one of several types.
Defining union with | (pipe symbol)
                  
                    let xname: string | number | boolean = 'saten';
                    xname = 'chauhan';
                    xname = 36;
                    xname = true;
                    // console.log(xname);

                    let aname: string = 'Chauhan';
                    let bnum: number = 40;
                    let cname: boolean = true;

                    // let xyz: string | number | boolean = aname | bnum | cname;

                    const showValue = (
                      value: string | number | boolean
                    ): string | number | boolean => {
                      console.log(value);
                      return value;
                    };

                    showValue('I am a mobile and web app developer');
                    showValue(786);
                    showValue(true);

                    const showData = (
                      value: string,
                      padding: number | number
                    ): string | number | boolean => {
                      console.log(value);
                      return value + padding;
                    };

                    showData('I am from Ayodhya, Uttar Pradesh', 30);
                  
                

Tuples Type

Tuples are a data structure that allow us to store a fixed size for collection of elements of different types.
They are similar to array.
The types of element in a tuple are fixed and declare at the time of creation.
using tuple can define element soecific order and type.
Order and Types matter in tuples.
                  
                   // Defining tuples type for user information
                    type UserInfo = [string, number, string, string, string, boolean];

                    // Defining tuples type for user information with readonly which mean we can update data structure in tuples
                    type PersonInfo = readonly [string, number, string, string, string, boolean];

                    const userData: UserInfo = [
                      'saten',
                      36,
                      'Kanpur',
                      'Uttar Pradesh',
                      'India',
                      true,
                    ];

                    userData.push('Raman');
                    console.log(userData);
                    const displayInfo = (user: UserInfo): void => {
                      const [name, age, city, state, country, drivinLicense] = user;
                      console.log(
                        `I am ${name}, ${age}, form ${city}, ${state}, ${country}, having driving license ${drivinLicense}`
                      );
                    };

                    displayInfo(userData);

                  
                

Generic Types

Generic types in typescript allow us to create reusable and flexible componenets or function that can work with multiple data types.
Basic Generics allows creating 'types variables which can be used to create class, functions and types aliases.
Generic makes it easier to write reusable code.
                  
                      function show(value: T): T {
                        return value;
                      }

                      const result1 = show(60);
                      const result2 = show('Pratap');
                      const result3 = show(true);

                      // console.log(result2);

                      function showResult(name: T, city: S) {
                        return typeof name == 'number' ? name + +city : `${name}, ${city}`;
                      }

                      const r1 = showResult('Singh', 120);
                      const r2 = showResult('Singh', 'Chauhan');
                      const r3 = showResult(40, 120);
                      const r4 = showResult('isAdmin', true);
                      // console.log(r1);
                      // console.log(r2);
                      // console.log(r3);
                      // console.log(r4);

                      // console.log(data1.name);

                      interface DemoData {
                        name: S;
                        city: S;
                        age: T;
                        isAdmin: B;
                      }

                      const myData: DemoData = {
                        name: 'Saten Singh',
                        city: 'Hyderabad',
                        age: 36,
                        isAdmin: true,
                      };

                      function getData(user: DemoData) {
                        console.log(user);
                      }

                      getData(myData);
                  
                

Typeof

Typeof
                  
                    /* typesof */
                    let s: string = 'saten';
                    let n: number = 12;
                    let und: undefined = undefined;
                    let b: boolean = true;
                    const f = () => 'Hello world';
                    let a: number[] = [1, 2, 3, 4];
                    typeof s === 'string'; // string
                    typeof n === 'number'; //number
                    typeof b === 'boolean'; // boolean
                    typeof undefined === 'undefined'; //undefined
                    typeof f === 'function'; //function
                    Array.isArray(a); // array
                  
                

Inference

Automatically will declare and assign type to object, when we do not define data type
                  
                  //Type inferences
                  const name = 'saten'; //Automatically will declare and assign type to object
                  
                

Call Signature

Call signature to declare and define the method inside object type with parameter and return types but implementation and body function.
                  
                    type Students = {
                      name: string;
                      age: number;
                      gender?: string;
                      greet: (country: string) => string; // Call Signature
                    };

                    const student: Student = {
                      name: 'saten',
                      age: 36,
                      greet: (country): string =>
                        `I am ${student1.name},  and I am ${student1.age} years old,  from ${country}`,
                    };
                  
                

Optional Chaining

Typescript chaining is the process of searching and calling varaiables, methods, parameters that might be nil in existence.
                  
                    parameter_name? : return_type;