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

Explore JavaScript prototype data sharing and method sharing implementation

Data Sharing What kind of data needs to be writte...

Linux cut command explained

The cut command in Linux and Unix is ​​used to cu...

Learn MySQL execution plan

Table of contents 1. Introduction to the Implemen...

Case analysis of several MySQL update operations

Table of contents Case Study Update account balan...

Use of MySQL query rewrite plugin

Query Rewrite Plugin As of MySQL 5.7.6, MySQL Ser...

Implementing a simple Gobang game with native JavaScript

This article shares the specific code for impleme...

Idea configures tomcat to start a web project graphic tutorial

Configure tomcat 1. Click run configuration 2. Se...

Sample code for installing ElasticSearch and Kibana under Docker

1. Introduction Elasticsearch is very popular now...

Implementation of vue-nuxt login authentication

Table of contents introduce Link start Continue t...

VMware configuration hadoop to achieve pseudo-distributed graphic tutorial

1. Experimental Environment serial number project...

What does mysql database do?

MySQL is a relational database management system....

Detailed explanation of JavaScript prototype and examples

Table of contents The relationship between the co...

A brief discussion on several ways to pass parameters in react routing

The first parameter passing method is dynamic rou...

MySQL 8.0.12 installation and configuration method graphic tutorial (windows10)

This article records the installation graphic tut...