This is the fourth day of my participation in the First Challenge 2022, for more details: First Challenge 2022 “.

Overloading understanding

Corresponding to different parameters are used to implement different parameters input and output function, signed a previously defined more overloading in an implementation of the signature, a function structure, overloading signature mainly show the functions of input and output precision, realize the signature is mainly to do the all types of input and output a full capacity definition, prevent TS compiler error, The body of a function is the entire logic of the entire function implementation.

Function overloading

Application example: In a class with a large number of students, the teacher wanted to query the user information of the students. If the student id was entered, the teacher matched the user information of the students by the id; if the student string was entered, the teacher matched the user information by the score. TS was used to simulate the situation. First define the user type

type User={
    id:number,
    name:string,
    age:number,
    grades:number
}
Copy the code

Class user information data

const userList:User[]=[
    {id:1.name:"Xiao Ming".age:20.grades:'98'},
    {id:2.name:"Xiao Ming".age:20.grades:'98'},
    {id:3.name:"Xiao Ming".age:20.grades:'98'},
    {id:4.name:"Xiao Ming".age:20.grades:'98'}]Copy the code

1. General implementation ideas

Input and output definitions are made by combining types. Enter number is (id) to be a unique ranking, use find; If the string is (grades), use filter.

function getUserInfo(value:number|string) :User|User[]{
    if(typeof value==='number') {return userList.find(item= >item.id===value)
    }else{
        return userList.filter(item= >item.grades===value)
    }
}
Copy the code

Defining TS this way will raise an exception

The reason is to cut to the source of the underlying find method and find that it is possible to return undefined type

The solution is very simple, return type and a undefined can be solved.

Disadvantages: The disadvantages are clear, both through the combination of type input and output, clearly know that the number input must return User, string input must return User[], this return is not clear input what to return what, many times we want to look at the definition of the method to see what to return what input, better determine the type. In order to solve this function overload occurs

2. The idea of function overload

TS function overloading is mainly divided into multiple overload signature + implementation signature + function body

TS checks all types and function bodies to see if there is a comparison. After the implementation signature and function body check is passed, the execution of the function is actually an overloaded signature + function body, skipped the implementation signature.

function getUserInfo(value:number) :User|undefined
function getUserInfo(value:string) :User[]
function getUserInfo(value:number|string) :User|User[] |undefined{
    if(typeof value==='number'){
        return userList.find(item=>item.id===value)}else{
        return userList.filter(item= >item.grades===value)
    }
}
Copy the code

By clicking on getUserInfo(2),command+ right mouse button, it will automatically parse to the number overload signature, which is intuitive to know how to call.

Requirement change: now there are too many queries for the same score, the teacher input string to add a variable count to control the number of queries.

The default value of count can be added to the signature. The default value of count can be added to the signature. The default value of count can be added to the signature.The specific implementation source code is as follows

function getUserInfo(value:number) :User|undefined
function getUserInfo(value:string,count:number) :User[]
function getUserInfo(value:number|string,count:number=1) :User|User[] |undefined{
    if(typeof value==='number'){
        return userList.find(item=>item.id===value)}else{
        return userList.filter(item= >item.grades===value).slice(0,count)
    }
}
getUserInfo('98'.3)
Copy the code

Method overloading

Method overloading is similar to function overloading, but method overloading is an example of how it can be used in a class: simply encapsulating an array to make it easier to use, returning index by index deletion, and returning object by object deletion

class ArrayEN {
  constructor(public arr: object[]) {}

  get(Index: number) {
    return this.arr[Index];
  }
  delete(value: number): number;
  delete(value: object): object;
  delete(value: number | object): number | object {
    this.arr = this.arr.filter((item, index) = > {
      if (typeof value === "number") {
        returnvalue ! == index; }else {
        return value !== item;
      }
    });
    returnvalue; }}Copy the code

Constructor heavy load

The constructor returns no value. It implicitly returns this, which is assigned to the variable to the left of the new object. So far all this points to the object that is currently in use.

Constructor reloading is basically the same as function overloading, with the main difference being that neither the TS class constructor reloading signature nor the implementation signature need to manage the return value. The TS constructor is executed after the object has been created, but before assigning values to object variables. It is typically used to assign values to object attributes. Example of application: Now I want to calculate the area of a picture, which can be a parameter, an object, or a length and width

interface OJType{ width? :number, height? :number }class Graph{
    public width:number;
    public height:number;

    constructor(width? :number,height? :number)
    constructor(side? :OJType)
    constructor(v1:any,v2? :any) {if(typeof v1==='object') {this.width=v1.width;
            this.height=v1.height
        }else{
            this.width=v1;
            this.height=v2; }}getArea(){
        const {width,height}=this;
        return width*height
    }
}

const g=new Graph(10.10);
console.log(g.getArea())
Copy the code

The main implementation idea is to define the type through the constructor, first is the type with the length and width of the object, which is defined in the form of interface, then is the width,heihgt number type, and finally simply through typeod to determine the type of the object and then assign the value. In summary, we find that whether function overload, method overload, Constructor heavy load is the same, just need to pay attention to the use of the scene, in vue3 source a lot of places are used, so there are a lot of scenes can be used, behind will continue to dig some of the CONTENT of TS.