1
头图
Hi! Hello everyone! I am a forensic doctor, a front-end code ape in the treatment department, talking to the code, listening to their voices, and looking forward to your praise and attention➕.

1. How to make type constraints

The type constraint is actually very simple, just add : type to the variable, function parameter, and function return value position.

give a chestnut 🌰: variables

//我们定义变量的时候,肯定是知道这个变量是存放什么类型的数据

let name:string = "法医";

Once you assign other types to name, an error will be prompted immediately

image.png

Give a chestnut 🌰: Function parameters and return values

//参数后面 :number表示传的参数必须是数字类型,而test函数后面的 :number表示返回值是数字类型
function test(a:number,b:number):number {
    return a + b;
}
test(1,2);//当调用test函数传值为数字表示可以正常运行,传其它类型则会报错

An error will be reported if the string is passed in

image.png

When we write a function, we are very clear about the type of the function's parameters and return value. At this time, we can constrain the type. We can call the function with confidence in subsequent calls, because as long as the wrong is written, we will immediately an error, without waiting for the program to run after an error, these JS is impossible, but it in TS easily can be done, not only so, type checking also bring many benefits, for example:

give a chestnut 🌰:

In JS , we have no way to determine that text(1,2) following code is called a function. It is possible that test will be modified in the middle, and then an error will be reported when the function is called

function test(a,b) {
    return a + b;
}
// 很多行代码
test = 123;
// 很多行代码
test(1,2);

image.png

But TS in this case is absolutely not allowed 🙈

image.png

Since TS knows that the function test and the calling function test are the same thing, a magical effect appears-when the function needs to be renamed, double-click the function test and press F2 , the function name is changed, and the calling function name also follows Changed, the reason for this effect is that TS has a strict type checking system. It knows that the test that calls the function is the test function, and there is a connection between the two

GIF 2021-9-7 15-34-20.gif

Not only that, but there is also an effect: when we call the function and press F12 , it will jump to the defined function position,

GIF 2021-9-7 15-43-12.gif

In order to let us write less code, when using TS for constraints, TS can complete type derivation in many scenarios

give a chestnut 🌰:

When we remove the function return value constraint, we can still find from the prompt that the return value is number . This is because we constrain the parameter to number , and the number and the number are still numbers, so the function will also return number and assign it to the variable. the result, TS will intelligently find the results returned by the function is number , so result type is also number , so we only need to add the type parameter constraints position on it, TS have type checking in every place, is not very cow Forced 🐮

GIF 2021-9-8 12-58-32.gif

📢 Here comes the question: How do I know when this type of derivation will succeed and when will it fail?

👉 Answer:

Is a tip, when we see the parameters of variables or functions appear three small points, which three points is a reminder: Be careful that you give me, I do not do that, it indicates that no deduced in the end what is Type, can be represented by any type, then you need to manually constrain it,

image.png

any : indicates any type, for this type, TS does not perform type checking

2. Basic types

Note that the first letter is lowercase

  • number: number,

    let figure:number = 6;
  • string: string

      let user:string = "法医";
  • boolean: Boolean value

      let fake:boolean = false;
  • array: array

    :number[] is actually syntactic sugar. The real wording is the second one below. Both of these two kinds of writing can constrain the array. It depends on personal preference. It is recommended to use the first one, because the angle brackets in react indicate components, Array<number> may be Cause conflict

      let arr:number[] = [1,2,3];
    
      let arr:Array<number> = [1,2,3];
  • object: object

    object constraint is not very commonly used, because object is not very binding. It can only constrain an object, but not the content inside the object, but it is sometimes used

    //传入一个对象,输出value值
      function getValues(obj:object) {
       let vals = Object.values(obj);
       console.log(vals); // 输出 法医  18   
      }
      getValues({
       name:"法医",
       age:18
      })
  • null and undefined

    null and undefined need to be null and undefined are subtypes of all other types. They can be assigned to other types, but there are hidden dangers. The following method calls will report errors. Because the constraints are string and number and 061d50aaa136ec, the value is ed again. null and undefined , this is something we don't want to happen.

      let str:string = null;
      let nums:number = undefined;
      
      //下面都会报错,由于约束了是string和number,但是值又是null和undefined
      str.toLocaleUpperCase();
      nums.toString();

    👉 Solution:

    tsconfi.json in the 061d50aaa13733 configuration file: "strictNullChecks": true , you can get more stringent null type checking. null and undefined can't be assigned to other types, but can only be assigned to itself

    image.png

3. Other common types

  • Joint Type: Choose one of multiple types

    When either a variable that string and may undefined time can be used combined type that can be used in conjunction type of protection judged

    📢 type protection: After the type of a variable is judged, its exact type can be determined in the judgment sentence. tyoeof can trigger type protection, but it can only trigger simple and basic type protection, and there is no way for complex types Triggered
    let user:string | undefined;
    
    if(typeof user === "string"){
        //类型保护,当进入这个判断,TS一定会知道,此时user一定是字符串
    }
  • Viod type: usually used to constrain the return value of a function, which means that the function does not return any

    viod is also available in Js , which means that undefined is returned after computing an expression, but it TS . It is usually used to constrain the return value of a function, which means that the function does not return anything.

    function user():void{
        console.log("法医");
    }

    Of course, it is also possible to not restrict it, because it will be derived from the

    image.png

  • never type: usually used to constrain the return value of a function, which means that the function can never end

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

    type derivation of this function is problematic. The derivation type is viod because it will never end. The type should be never instead of viod , so it needs to be changed manually

    GIF 2021-9-8 16-37-29.gif

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

    Since it will never end, the following log function cannot be executed and the code cannot be accessed

    image.png

    There is also a situation that will never end, requiring manual constraints

    GIF 2021-9-8 16-53-09.gif

  • Literal type: use a value for constraint instead of type constraint

    //表示从此以后,变量name只能是 “法医”,别的就会报错
    let name:"法医";
![GIF 2021-9-8 17-18-55.gif](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5e0cde8988b24cb2b860f757236549be~tplv-k3u1fbpfcp-watermark.image)

一般我们可以用字面量类型对性别或者对象中的属性进行约束:

```js
//对gender 变量进行约束,只能是男或女,其它不行
let gender :"男" | "女";

//对users对象中的name和age属性分别约束为字符串和数字,下次给users赋值的时候,只能包含name和age
let users:{
    name:string
    age:number
}
```
  • Tuple type (Tuple): not much used, just understand it, it means a fixed-length array, and the type of each item in the array is determined

    //定义了一个变量为tupleType的数组,这个数组只能有两项,并且第一个必须为字符串,第二个必须为数字
    let tupleType:[string,number];
    
    //第一项必须为字符串,第二项必须为数字,只能有两项,否则报错
    tupleType = ["法医",5];
  • Any type: The any type can bypass the type check, so the any type can be assigned to any type, but there is definitely a hidden danger, because it cannot use the protection mechanism provided by TS, so it is not recommended to use the any type at will, in order to solve the any belt The question came, TS3.0 introduced the unknown type

    GIF 2021-9-8 19-19-54.gif

4. Type aliases

Give a new name to the known type to prevent repetitive writing of some codes

type Gender = "男" | "女";
type user = {
    name:string
    age:number
    gender:Gender
}

function getUser(g:Gender) {
    //...
}

5. Relevant constraints of the function

  • Function overloading

combine look at a function 061d50aaa13d33. The function is to multiply when two numbers are passed as parameters, and add when two strings are passed. If they are not the same, an error will be reported.

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和b必须是相同的类型")
}

There is no problem with the function itself. The problem occurs in the process of function call. When we write too much code, we may pass different types as parameters by mistake. What is more terrifying is that if the parameter is the return result of the function, it will be even more terrifying. Because of this, it is best to tell the calling function during the call of the function that it is either a number type or a string type.

GIF 2021-9-8 20-57-48.gif

Logically, the digital words are returned result is a digital type, the string is returned, then the result is a string type, however result type is string | number , can clearly be seen on the FIG., Such a case, there is no back The method uses the result variable, because it is clearly known that the result returned by numbers must be of numeric type, and those returned by string must be of string type. It means that the code prompt will not show the methods owned by all numbers or the methods owned by all strings, but only the methods owned by numbers and strings- toString and valueOf as shown below:

GIF 2021-9-8 21-06-21.gif

👉 solution:

Add the following two lines of code. These two lines of code are equivalent to telling TS combine function can only have two situations, one is that two numbers return numbers, and the other is that two strings return strings. These two lines of code function overload.

📢 Function Overloading: Before the function is implemented, a variety of functions are declared.
//加上这两句代码
/**
 * 得到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和b必须是相同的类型")
}

let result = combine("b","n");

After using function overloading, you can only pass two numbers or two strings when calling the function, otherwise an error will be reported, let's see the effect:

GIF 2021-9-8 21-23-10.gif

  • Optional parameters
📢 optional parameters: you can add the after some parameter names, which means that the parameter does not need to be passed. Optional parameters must be at the end of the parameter list

image.png

When there are three formal parameters and two are passed to the calling function, an error will be reported. TS is very strict and does not allow the number of parameters to be mismatched. Assuming that the third parameter can not be passed, add to indicate that it is an optional parameter

image.png


法医
129 声望16 粉丝

我很荣幸成为一名前端开发者,我不是大神,但我正在为之努力!