Typescript Introduction

  1. What is TypeScript

    TS is a superset of JavaScript. TS takes JS and adds new features and syntax to it. TS cannot be executed directly in JS environment (such as browser, node.js).

    TS is a programming language and a tool. It is a powerful compiler that compiles TS code into JS code. That is, the programmer writes TS code with all the new features and all the benefits, and the result is normal JS code.

    TS gives programmers the opportunity to find errors in their code while the browser is running, before the script is run. In other words, TS provides additional error checking during project development (compliation). This catches and fixes errors early on. JS can only find errors at runtime.


  2. TypeScript overview

    1. Types: Many mistakes can be avoided.

    2. Next-gen JS features: Use modern JS features and still generate and publish code that works in older browsers.

    3. TS-specific features: such as interfaces and Generics (generics).

    4. Meta-Programming features: such as Decorators.

    5. Rich Configuration Option: TS can be configured and fine-tuned according to requirements to make it more strict or loose.

    6. Can be supported in non-TS projects: via modern tools and modern IDEs.


  3. Why use TypeScript

    Since JS variables/constants have no type restrictions, the code execution results may be completely different from the original intention. For example:

    1
    2
    3
    4
    5
    function add(num1, num2){
    return num1 + num2;
    }
    console.log(add('2', '3')) //The result is 23 because it is string concatenation.
    console.log(add(input1.value, input2.value)) //This will make the error more subtle.

    If you want to solve this problem through JS, you need to add an if conditional judgment to verify the incoming parameters.

    But using TS, you can find errors while writing code.

    1
    2
    3
    4
    5
    function add(num1: number, num2: number){
    return num1 + num2;
    }
    console.log(add('2', '3')) //Report an error directly at this time
    console.log(add(+input1.value, +input2.value))

  4. Unary plus operator (+)

    In JavaScript, you can convert a value to a number using the unary plus operator (+). When the unary plus operator is used before a non-numeric value, JavaScript attempts to convert the value to a number. If the value cannot be converted to a number, NaN is returned.

    So if you use +input.value in JavaScript, it will try to convert the value of the input element (usually a string) to a numeric type. This can be used to ensure that the value obtained from the input element is of numeric type, rather than a string type, so that correct numerical calculations can be performed in subsequent calculations.


  5. A website that can convert TS code into JS code

    typescriptlang.org


Share