The generic

Why generics? What are the benefits of generics, see the following example

Video Tutorial Address

Don’t use a generic

class Lee {
    name: string = 'hanyun'

    say() {
        console.log(this.name)
    }
}

let lee = new Lee();
lee.say();
Copy the code

The results

hanyun

Copy the code

If you want to add an age attribute, a height attribute, you have to change more code

Generic writing

interface IUser {
    name: string
}

class Lee<IUser> {
    user: IUser
    constructor(user: IUser) {
        this.user = user
    }

    say() {
        console.log(this.user)
    }
}

let lee = new Lee({name: "hanyun"})
lee.say();
Copy the code

The results

{ name: 'hanyun' }
Copy the code

You add an age attribute, a height attribute, you just change the interface, you change the constructor, you don’t change the logic in the code

After looking at the examples above, you will feel that using generics is a lot of trouble and a lot of code! I not only have to define the interface, I also have to deal with the interface, what a hassle! Yes. At first glance, it was a lot of trouble, and so far it seems like a lot of work. But what about after a month? If you go back to your code, can you remember what you wrote? I don’t think so. The interface can help you remember a lot of things, it helps you to clean up the code logic, such as the above code, through the interface defined by the generic, let you know what attributes user, you change the code thinking clearly. At the same time, your IDE will give you code checks and hints, reducing your workload and saving you a lot of trouble.