Beginner TS - basic type of TS

Posted by puja on Thu, 30 Dec 2021 14:56:47 +0100

Basic type of TS

  • Boolean type

    • let isDo:boolean = true;   === var isDo = true
      
  • Number type

    • let num:number = 5; === var num = 5
      
  • String type

    • let name:string = 'mery'; === var name = 'mery'
      
  • Array type

    • let arr:number[] = [1,2,3]; === var arr =[1,2,3]
      
    • let arr:Array<number> = [4,5,6]; //Array < number > is a generic syntax
      
  • Enum type

    • Enumerations can be used to express intentions clearly or to create a distinct set of use cases. TS supports numeric and string based enumeration.

    • Numeric enumeration
      enum Dir{
          NORTH,
          SOUTH,
          EAST,
          WEST
      }
      let dir:Dir = Dir.NORTH;
      By default, NORTH The initial value of is 0, and the remaining members will grow automatically from 1.
      
      You can also set initial values, such as
      enum Dir{
          NORTH = 3,
          SOUTH,
          EAST,
          WEST
      }
      
    • String Enum 
      Allows us to use string enumeration. In a string enumeration, each member must be initialized with a string literal or another string enumeration member.
      
      enum Dir{
      NORTH = "NORTH",
      SOUTH = "SOUTH",
      EAST = "EAST",
      WEST = "WEST"
      }
      
  • Heterogeneous enumeration
     The member values of heterogeneous enumerations are a mixture of numbers and strings.
    enum Enum{
    A,B,C = "C",D = "D",E=6,F
    }
    
    console.log(Enum.A) //Output: 0
    console.log(Enum[0]) // Output: A
    //Numeric enumeration has more "reverse mapping" than string enumeration
    
  • Any type

    • In TS, any type can be classified as any type, which makes any type the top-level type of the type system, also known as the global supertype.

    • let noSure:any = 555;
      noSure = "mery";
      noSure = true;
      

      TS allows us to perform any operation on any type of value without performing any form of check in advance.

      let value:any;
      value.foo.bar; // OK
      value.trim(); //OK
      value(); //OK
      new value(); //OK
      value[0][1]; //OK
      

      With the any type, you can easily write code that is of the correct type but has problems at run time. If we use any type, we can't use a lot of the protection mechanisms provided by TS.

  • Unknown type

    • All types can be assigned to unknown.

    • let value:known;
      
      value =true ;// ok
      value = 42; //ok
      value = 'hello world'; //ok
      value = []; //ok
      value = {}; //ok
      value = null; //ok 
      value = undefined; //ok 
      value = new TypeError(); //ok
      value = Symbol("type"); // ok
      
      let value1: unknown = value; // OK
      let value2: any = value; // OK
      let value3: boolean = value; // Error
      let value4: number = value; // Error
      let value5: string = value; // Error
      let value6: object = value; // Error
      let value7: any[] = value; // Error
      let value8: Function = value; // Error
      

      All assignments to the value variable are considered to be of the correct type. However, unknown type can only be assigned to any type and unknown type itself. Only containers that can hold values of any type can hold values of type unknown.

      let value: unknown;
      
      value.foo.bar; // Error
      value.trim(); // Error
      value(); // Error
      new value(); // Error
      value[0][1]; // Error
      

      After setting the value variable type to unknown, all the default configurations that allow all changes have been changed to prohibit any changes.

  • Tuple type (tuple)

    • To store different types of values in a single variable, you need to use tuples. Tuples are unique types in TS and work like arrays.

    • Can be used to define types with a limited number of unnamed properties, each with an associated type. When using tuples, you must provide the value of each attribute.

    • let tupleTypr:[string,boolean];
      tupleType = ['mery',true];
      //The tupleType variables are initialized according to the correct type. Like the array, we can access the elements in the tuple through subscripts.
      
      During tuple initialization, if there is a type mismatch, an error will be prompted. You must also provide the value of each attribute, or an error will occur.
      
  • Void type

    • Void type means that there is no type. When a function has no return value, you will see that its return value type is void.

    • // Declare that the return value of the function is void
      function warnUser(): void {
        console.log("This is my warning message");
      }
      

      It is worth noting that declaring a variable of void type is useless because its value can only be undefined or null

  • Null and Undefined types

    • Undefined and null have their own types, undefined and null respectively

    • let u:undefined = undefined;
      let n:null = null;
      

      By default, null and undefined are subtypes of all types. We can assign null and undefined to variables of type number. However, if the – strict tag is specified, null and undefined can only be assigned to void and their respective types.

  • Never type

    • Never types represent the types of values that never exist. For example, never types are the return value types of function expressions or arrow function expressions that always throw exceptions or have no return value at all.

    • // The function returning never must have an unreachable end point
      function error(message: string): never {
        throw new Error(message);
      }
      
      function infiniteLoop(): never {
        while (true) {}
      }
      
      
    • In TS, the feature of never type can be used to realize comprehensive inspection

    • type Foo = string | number;
      
      function controlFlowAnalysisWithNever(foo: Foo) {
        if (typeof foo === "string") {
          // Here foo is narrowed to string type
        } else if (typeof foo === "number") {
          // Here foo is narrowed to number type
        } else {
          // foo here is never
          const check: never = foo;
        }
      }
      
      

Topics: Javascript TypeScript ts