Types - primitive, object

  1. Core Types

    Primitive types: number, string, boolean

    reference types: object, Array

    TS exclusive typs: Tuple, Enum, any

    Primitive types are written in TS as parameter: type, such as n1: number.


  2. Type Casting case issue

    In TS, core primitive types are always lowercase, such as string, number, etc. String, Number, etc. will not appear.


  3. TS type inference

    1
    2
    3
    const number1 = 5;
    const printResult = true;
    const string1 = "Result is: ";

    Why is there no type written in the above code? As written:

    1
    2
    3
    4
    const number1: number = 5;
    const printResult: boolean = true;
    const string1: string = "Result is: ";
    //You can write it like this, but it is redundant and not a good practice.

    This is because TS has a built-in feature called type inference. This means that TS understands variables and constants because the programmer initialized the variable/constant with a number/boolean/string. Hover the mouse over the variable to see the inferred type.

    Only when variables/constants are not initialized, do you need to manually write the type, such as:

    1
    let number2: number;

  4. TS support for object types

    TS infers the object type. That is, for the properties in the object, there is type inference.

    If you want to use an attribute that is not in the object, TS will directly report an error.

    If you manually set the type of the object, for example, just set it to object without writing the internal attribute type of the object, an error will also be reported when using the existing attributes in the object:

    1
    2
    3
    4
    5
    const person: object = {
    name: "Derek",
    age: 18
    };
    console.log(person.name); //error report

    Therefore, to manually set the object type, it should be written as:

    1
    2
    3
    4
    5
    6
    7
    const person: {
    name: string;
    age: number;
    } = {
    name: "Derek",
    age: 18
    }; //Correct writing

  5. Nested objects

    When encountering a nested object, the types can be directly nested layer by layer.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    {
    id: string;
    price: number;
    tags: string[];
    details: {
    title: string;
    description: string;
    }
    }

Share