Detailed explanation of generic cases in TypeScript

Detailed explanation of generic cases in TypeScript

Definition of Generics

// Requirement 1: Generics can support unspecified data types, requiring that the parameters passed in and the returned parameters are consistent // Although this method can achieve consistency between the parameters passed in and returned, it loses the type parameter check/*
function getData(value: any): any {
    return "success"
}
*/

// Define generics to solve requirement 1 // T represents generics (the capital letter here can be defined arbitrarily, but it is generally T by default) The specific type is determined when this method is called function getData<T>(value: T):T{
    return value;
}

//Incoming string type var get = getData<string>("hello")
console.log(get)

// The type passed in is a number var getTwo = getData<number>(666)
console.log(getTwo)

// Requirement 2: For example, there is a minimum heap algorithm that needs to support returning both numbers and strings. This can be achieved through class generics. // Define class generics class minCla<T> {
    list: T[] = [];

    add(value: T):void {
        this.list.push(value);
    }

    min(): T {
        var minNum = this.list[0];
        for(var i=0; i<this.list.length; i++) {
            if (minNum > this.list[i]) {
                minNum = this.list[i]
            }
        }
        return minNum
    }
}

var minNum = new minCla<number>();
minNum.add(2);
minNum.add(1);
minNum.add(7);
console.log(minNum.min()); // returns 1


// Characters are compared by ASCII code var minNumTwo = new minCla<string>();
minNumTwo.add("c");
minNumTwo.add("z");
minNumTwo.add("a");
console.log(minNumTwo.min()) // Returns a

Generic Interface

// Two ways to implement generic interfaces // Method 1:
// Define a generic interface interface Func {
    <T>(value: T): T
}

// Define a function to implement the generic interface var f: Func = function<T>(value: T) {
    return value;
}
f<string>("hello")
f<number>(666)

// Method 2:
interface FuncONe {
    <T>(value: T): T
}

var f1: FuncONe = function<T>(value: T):T {
    return value;
}

f1<string>("world")
f1<number>(666)

Implementing Generic Classes

/*
1. Define a User class, which is used to map database fields. 2. Then define a MysqlDb class, which is used to operate the database. 3. Then pass the User class as a parameter into MysqlDb. */

/*Version 1:
class User {
    usernam: string | undefined;
    password: string | undefined;
}

class MysqlDb {
    add(user: User): boolean {
        console.log(user);
        return true;
    }
}

var u1 = new User();
u1.usernam = "pika";
u1.password = "pika"

var msql = new MysqlDb();
msql.add(u1);
*/

// However, the tables and databases defined above cannot guarantee the correctness of the incoming data // Version 2 // Define the generic class MysqlDb <T>{
    add(info: T): boolean {
        console.log(info);
        return true;
    }
}

// Define a user class and map it to the database class User {
    usernam: string | undefined;
    password: string | undefined;
}

var u1 = new User();
u1.usernam = "pika";
u1.password = "pika"

// Instantiate a database (the class is used as a parameter to constrain the type of the incoming parameter)
var msql = new MysqlDb<User>();
msql.add(u1); // Ensure that the format of the incoming data is of User type

Comprehensive Case

need:
Function: Define a database operation library to support Mysql MongoDb
Requirement 1: Mysql and MongoDb have the same functions, both have add, update, delete and get methods. Note: Constrain unified specifications and code reuse solutions: Constraint specifications are needed so interfaces must be defined, and code reuse is needed so generics are used. 1. Interface: In object-oriented programming, an interface is a specification definition that defines the specifications of behaviors and actions. 2. Generics: Popular understanding: Generics are to solve the reusability of class interface methods*/

// Implementation process:
// Define an interface to constrain all methods interface DbMethod<T> {
    add(info: T): boolean;
    update(info: T, id: number): boolean;
    delete(id: number): boolean;
    get(id: number): boolean;
}

// Define a Mysql database class. Note: To implement a generic interface, this class should also be a generic class class MysqlDbs<T> implements DbMethod<T> {
    add(info: T): boolean {
        console.log(info);
        return true;
    }    
    
    update(info: T, id: number): boolean {
        var obj = {
            username: "xxxx",
            password: "666"
        }
        return true
    }

    delete(id: number): boolean {
        console.log("delete success");
        return true
    }
    
    get(id: number): boolean {
        var arr = [
            {username: "xxx",
            password: "xxxxx"
            }
        ];
        return true
    }
}
// test:
class Users {
    username: string | undefined;
    password: string | undefined;
};

// Use the Users class to constrain the correctness of the parameters passed in var mysql = new MysqlDbs<Users>();
var u = new Users();
u.username = "xxxx"
u.password = "xxxxxx"
//Simulate the addition, deletion, modification and query of the database mysql.add(u);
mysql.get(1);
mysql.update(u, 1);
mysql.delete(1)



// Define a MongoDb database class. Note: To implement a generic interface, this class should also be a generic class class MongoDb<T> implements DbMethod<T> {
    add(info: T): boolean {
        console.log(info);
        return true;
    }    
    
    update(info: T, id: number): boolean {
        var obj = {
            username: "xxxx",
            password: "666"
        }
        return true
    }

    delete(id: number): boolean {
        console.log("delete success");
        return true
    }
    
    get(id: number): boolean {
        var arr = [
            {username: "xxx",
            password: "xxxxx"
            }
        ];
        return true
    }
}

// test:
class Userd {
    username: string | undefined;
    password: string | undefined;
};

// Use the Users class to constrain the correctness of the parameters passed in var mysql = new MongoDb<Userd>();
var u = new Userd();
u.username = "xxxx"
u.password = "xxxxxx"
//Simulate the addition, deletion, modification and query of the database mysql.add(u);
mysql.get(1);
mysql.update(u, 1);
mysql.delete(1)

This is the end of this article about the detailed case analysis of generics in TypeScript. For more relevant content about generics in TypeScript, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to explain TypeScript generics in a simple way
  • TypeScript generic parameter default types and new strict compilation option
  • In-depth understanding of Typescript generic concepts in the front end
  • Teach you how to use webpack to package and compile TypeScript code
  • In-depth understanding of the use of the infer keyword in typescript
  • Why TypeScript's Enum is problematic

<<:  Detailed explanation of MYSQL database table structure optimization method

>>:  Solve the problem of case sensitivity of Linux+Apache server URL

Recommend

Use of VNode in Vue.js

What is VNode There is a VNode class in vue.js, w...

Summary of pitfalls encountered in installing mysql and mysqlclient on centos7

1. Add MySQL Yum repository MySQL official websit...

How to change the domestic image source for Docker

Configure the accelerator for the Docker daemon S...

How to quickly paginate MySQL data volumes of tens of millions

Preface In backend development, in order to preve...

Simple implementation method of Linux process monitoring and automatic restart

Purpose: Under Linux, the server program may be d...

How to add a column to a large MySQL table

The question is referenced from: https://www.zhih...

Detailed explanation of mixed inheritance in Vue

Table of contents The effect of mixed inheritance...

Detailed explanation of the 4 codes that turn the website black, white and gray

The 2008.5.12 Wenchuan earthquake in Sichuan took...

Detailed explanation of MySQL data rows and row overflow mechanism

1. What are the formats of lines? You can see you...

Troubleshooting and solutions for MySQL auto-increment ID oversize problem

introduction Xiao A was writing code, and DBA Xia...

Talk about nextTick in Vue

When the data changes, the DOM view is not update...

Detailed explanation of Linux text editor Vim

Vim is a powerful full-screen text editor and the...

CSS Back to Top Code Example

Most websites nowadays have long pages, some are ...

Linux uses NetworkManager to randomly generate your MAC address

Nowadays, whether you are on the sofa at home or ...