Types - any, unknown, never

  1. any

    The any type is the most flexible type specified in TS, and any basically ensures that the TS compiler cannot check anything. But any also takes away all the benefits brought by TS and should be avoided as much as possible.


  2. unknown

    unknown is more strict than any. unknown is better than any when assigning a value of unknown type to a value of fixed type. The difference is:

    1. Assignability

      A value of type any can be assigned to a variable of any type, and a value of any type can be assigned to a variable of type any , which means that the any type can easily interact with other types.

      Values of unknown type cannot be directly assigned to variables of other types, nor can values of other types be directly assigned to variables of unknown type. Type checking or type assertion is required before assignment can be made.

      1
      2
      3
      4
      5
      6
      let userInput: unknown;
      let userName: string;

      userInput = 5;
      userInput = "Derek";
      userName = userInput; //Error report. If the userInput type is any, no error will be reported.

    1. Type Inference

      When using the any type, TypeScript does not type check or type infer the variable or value, which means that the any type may mask potential type errors.

      When using an unknown type, TypeScript performs type checking and type inference on the variable or value, which can help developers better catch potential type errors.


    1. Type Safety

      The TypeScript compiler does not enforce type checking when using the any type, which can lead to potential runtime errors.

      The TypeScript compiler enforces type checking when using unknown types, which can help developers avoid potential runtime errors.


    To sum up, the main differences between any and unknown types are in assignability, type inference and type safety. In TypeScript, you should try to avoid using any type. Instead, use unknown type and perform type checking or type assertion when necessary.


  3. never

    Never is the type of function. It means that the function never generates a return value, such as the function directly throws an error, etc. Throwing an error causes the script to crash, so a return value is never generated.

    1
    2
    3
    function generateError(message: string, code: number): never {
    throw {message: message, errorCode: code};
    }

Share