hi! Everybody is good! I am a medical examiner, a treatment department front-end code ape 🐒, dialogue with the code, listen to the voice of their heart, looking forward to everyone’s praise 👍 and attention ➕.

1. How do type constraints work

The type constraint is as simple as adding: type to a variable, function argument, or function return value.

For example 🌰 : variables

// When we define a variable, we must know what type of data the variable holds

let name:string = "Forensic";
Copy the code

Any time you assign a different type to name, an error immediately occurs

For example 🌰 : function arguments and return values

// Number indicates that the parameter passed must be numeric, and number indicates that the return value is numeric
function test(a:number,b:number) :number {
    return a + b;
}
test(1.2);// If you call test and pass it as a number, it will work fine. If you pass other types, an error will be reported
Copy the code

An error is reported when a string is passed in

When we write a function, we can clearly see that the function of the parameters and what kind of, the return value is good at this point we can constraint type, later in the call we can rest assured in the calling function, as long as the write wrong, immediately will prompt error, do not need to wait until after the program is running errors, these is made in JS, In TS, however, it is easy to do, and there are many benefits to type checking, such as:

For example 🌰 :

In javascript, there is no way to confirm that test(1,2) is calling a function

function test(a,b) {
    return a + b;
}
// Many lines of code
test = 123;
// Many lines of code
test(1.2);
Copy the code

But in TS this is definitely not allowed 🙈

Because the TS know function test and the function test is the same thing, so there is a magical effect, when need to rename () function, double-click the function test and press F2, function name changed, changed, invoke the function name, followed is achieve this effect, because TS have strict type checking system, It knows that the test function is called by test, and there is a connection between the two

Not only that, there’s another effect: when we click to call a function and press F12, it jumps to the function defined,

In order to save us some code, TS can do type derivation in many scenarios when using TS constraints

For example 🌰 :

When we remove the constraint on the return value of the function, we can still see from the prompt that the return value is “number”. This is because we set the constraint on the parameter to “number”, and the sum of the numbers is still a number. Therefore, the function will also return “number” and assign a value to the variable “result”. TS is also smart enough to recognize that the function returns a number, so the result type is also number, so we only need to put type constraints on the argument position. TS has type checking everywhere, isn’t it awesome 🐮

📢 Which begs the question: how do I know when this type of derivation succeeds and when it fails?

👉 answer:

There’s a little trick, when you see three little dots in a variable or a function argument, and these three little dots are saying, “Be careful, I really can’t do this,” and that means you haven’t derived what type it is, you can use any, and then you have to manually constrain it,

Any: indicates any type. For this type, TS does not perform type check

2. Basic types

Notice that the first letter is lowercase

  • -Leonard: The number,

    let figure:number = 6;
    Copy the code
  • String: string

    let user:string = "Forensic";
    Copy the code
  • Boolean: Indicates a Boolean value

    let fake:boolean = false;
    Copy the code
  • Array: an array of

    React :number[] :number[] :number[] :number[] :number[] :number[] :number[

    let arr:number[] = [1.2.3];
    
    let arr:Array<number> = [1.2.3];
    Copy the code
  • Object: the object

    The object constraint is not very common because it is not very binding. It can only restrict an object, but not its contents, but is sometimes used

    // Pass in an object and print value
    function getValues(obj:object) {
       let vals = Object.values(obj);
       console.log(vals); // Output forensic 18
    }
    getValues({
       name:"Forensic".age:18
    })
    Copy the code
  • Null, and undefined

    It is important to note that null and undefined are subtypes of all other types. They can be assigned to other types, but there is a danger that the following method calls will return an error. This is something we don’t want to happen.

    let str:string = null;
    let nums:number = undefined;
    
    // All errors will be reported, because the constraint is string and number, but null and undefined
    str.toLocaleUpperCase();
    nums.toString();
    Copy the code

    👉 Solution:

    Json configuration file with “strictNullChecks”: true to get more strict null type checks, null and undefined can not be assigned to other types, only to themselves

3. Other common types

  • Union type: Choose from any of several types

    Associative types can be used when a variable can be either a string or undefined, which can be used in conjunction with type protection

    📢 Type protection: When the type of a variable is judged, its exact type can be determined in the judgment statement. Tyoeof can trigger type protection, but it can only trigger simple and basic type protection, complex type is not triggered

    let user:string | undefined;
    
    if(typeof user === "string") {// Type protection, when entering this judgment, TS must know that user must be a string
    }
    Copy the code
  • Viod type: Usually used to constrain the return value of a function to indicate that the function does not return anything

    Viod is also used in Js, which means to evaluate an expression and return undefined, but in TS it has a different meaning. It is usually used to constrain a function to return a value, indicating that the function does not return anything

    function user() :void{
        console.log("Forensic");
    }
    Copy the code

    Of course, it’s ok to have no constraint, because you can type it out

  • Never type: Usually used to constrain the return value of a function to indicate that the function can never end

    function thorwError(msg:string) {
        throw new Error(msg)
    }
    Copy the code

    The type derivation of this function is problematic, the type of the derivation is viod, and since it never ends, the type should be never instead of viod, so it needs to be changed manually

    function thorwError(msg:string) :never {
       throw new Error(msg)
    }
    Copy the code

    Since it never ends, the following log function cannot execute and access the code

    There are also cases that never end and require manual constraints

  • Literal types: Use a value instead of a type constraint

    From now on, the variable name can only be "forensic", otherwise an error will be reported
    let name:"Forensic";
    Copy the code

    In general we can use literal types to constrain gender or attributes in objects:

    // Constrain the gender variables, only male or female, nothing else
    let gender :"Male" | "Female";
    
    // Restrict the name and age attributes in the Users object to a string and a number, respectively. The next assignment to Users can contain only name and age
    let users:{
        name:string
        age:number
    }
    Copy the code
  • Tuple: an array of fixed length in which each item is typed

    // Define an array of tupleType variables. This array can have only two items, and the first must be a string and the second must be a number
    let tupleType:[string,number];
    
    // The first item must be a string, and the second item must be a number
    tupleType = ["Forensic".5];
    Copy the code
  • Any: The any type can bypass type checking. Therefore, any can be assigned to any type. However, it is not recommended to use any because it does not use the protection provided by TS

4. Type alias

Give known types new names to prevent duplication of code

type Gender = "Male" | "Female";
type user = {
    name:string
    age:number
    gender:Gender
}

function getUser(g:Gender) {
    / /...
}
Copy the code

5. Related constraints of functions

  • Function overloading

Let’s take a look at the combine function, which can produce an error if two numbers are passed as arguments and two strings are added together.

function combine(a:number | string,b:number | string) :number | string {
    if(typeof a === "number" && typeof b === "number") {return a * b;
    }
    else if(typeof a === "string" && typeof b === "string") {return a + b;
    }
    throw new Error("A and B must be of the same type.")}Copy the code

Function itself is no problem, the problem occurs in the process of function calls, when after the code we write more, we might mistake pass different types as parameters, is more terrible if the parameter is function returns as a result, it would be, therefore, in the process of function calls had better tell the function, either are numeric type, or is a string type.

Logically, all Numbers you return, is the result of the digital type is string is returned if the result is a string type, however the result is of type string | number, pictured above, can see clearly that this kind of circumstance, there was no way to use behind the result variable, Because you know that if you’re going to return a number you’re going to return a number, you’re going to return a string you’re going to return a string. This means that the code prompt will not show methods owned by all numbers, or methods owned by all strings, but only methods owned by both numbers and strings — toString and valueOf as shown below:

👉 Solution:

Add the following two lines of code, which tell TS that the Combine function can only have two cases, one where two numbers return a number, and the other where two strings return a string, and these two lines are called function overloading.

📢 function overloading: Multiple cases of a function call are declared before the function is implemented.

// Add these two lines of code
/** * get a * b *@param a 
 * @param b 
 */
function combine(a:number,b:number) :number;
/** * a + b *@param a 
 * @param b 
 */
function combine(a:string,b:string) :string;

function combine(a:number | string,b:number | string) :number | string {
    if(typeof a === "number" && typeof b === "number") {return a * b;
    }
    else if(typeof a === "string" && typeof b === "string") {return a + b;
    }
    throw new Error("A and B must be of the same type.")}let result = combine("b"."n");
Copy the code

When a function is called, only two numbers or two strings will be passed, otherwise an error will be reported.

  • Optional parameters

📢 Optional: You can add? After some parameter names. Number, indicating that this parameter may not be passed. Optional arguments must be at the end of the argument list

An error is reported when a function is called with three parameters but passes two. TS is strict and does not allow mismatches in the number of parameters. Suppose the third argument is not passed, add a? The number indicates that this parameter is optional