This is the 14th day of my participation in the August Text Challenge.More challenges in August

Generic Generics

Generics is the property of defining functions, interfaces, or classes without specifying a specific type in advance, but specifying the type at the time of use. Generics create reusable components that can support multiple types of data, and users can use them with their own data types.

TypeScript on generics: In software engineering, we need to not only create consistent, well-defined apis, but also think about reusability. The ability of components to support not only current data types but also future data types gives you a lot of flexibility when building large systems

Generics can be defined using Angle brackets <>. In the following example,

helps capture the type passed in by the user. T can be assigned to the subsequent parameters value and return value as their type.




Generic method

Example: In this example, the getData method is called using the generic

. If you specify the type of the generic as number, you will get an error passing in a string. If you want to pass in a string, just specify T as string

function getdata<T> (value:T) :T {
    return value;
}
getdata<number>('1'); // Parameters of type "string" cannot be assigned to parameters of type "number"
getdata<number>(1);
getdata<string>('1');
Copy the code

A generic class

Generics can also be used in the definition of classes, which use (<>) to enclose the generic type after the class name.

Define a generic class:

class MyClass<T> {
    list:T[] = [];
    add(value:T):T{
        this.list.push(value);
        let max:T = this.list[0];
        this.list.map((item) = > {
            if(max <= item) { max = item; }})returnmax; }}Copy the code

Instantiate the class and specify by generics that the type T represents is number. Each time the add() method adds data, it returns the current maximum value. The added data type can only be number

let myc1 = new MyClass<number>();
myc1.add(10);
myc1.add(7);
myc1.add(18);
console.log(myc1.add(9)); / / 18
Copy the code

You can think of a class as a generic class for parameter types, define an App class as a parameter type passed in, define a Test and use generics for constraints.

class App {
    name: string | undefined;
}

class Test<T> {
    say(value: T):void {
        console.log(value); }}Copy the code

When defining an instance of the Test class, the App class is passed in as a generic constraint. As a result, an error will occur if the method parameter type is not specified by the App class.

let app = new App();
app.name = '123';

let test = new Test<App>();
test.say(app);
Copy the code




A generic interface

Define an interface with a type attribute specifying name

interface Inter<T> {
    index:number;
    name:T;
}

let newinter: Inter<string> = { index: 7.name: 'Joe' } 
Copy the code

Of course, if the generic interface is for functions, we can define it internally:

interface Inter<T, K> {
    (index:T, name:K):void;
}

let newinter = function<T.K> (index:T, name:K) :void {
    console.log(name);
}
let myinter:Inter<number, string> = newinter;
myinter(10.'bill')
Copy the code

Or you can define it directly inside the interface:

interface Inter {
    
      
       (index:T, name:K):void; } let myinter:Inter = newinter; Myinter (10, 'Li Si ')
      ,>Copy the code

Generic constraint

In the use of generics, since the type of a generic variable is not known in advance, its properties and methods cannot be manipulated arbitrarily.

For example, in the Test generic class above, we cannot use the. Length attribute if we print the value in the say method. If we print the value in the say method, we cannot use the. Length attribute.

This is because if you pass in a value of type number or Boolean, there is no length attribute

say(value: T):void {
    console.log(value.length);
}
Copy the code

At this point, we can use generic constraints (listing constraints on T).

Generic constraints use the extends keyword, similar to inheritance in classes and interfaces

Write an interface GenericsRules that internally sets the length property of type number.

The generic T of Test now requires a variable with the length attribute, otherwise an error will be reported. New Test

() cannot be used to define instances of Test.

interface GenericsRules {
    length: number;
}
class Test<T extends GenericsRules> {
    say(value: T):void {
        console.log(value.length); }}Copy the code


At the end of the page, it’s not just about TypeScript interface classes before, but about generics now. These are all I just learned, if you want to master, certainly need to practice and use their own, rather than this study is good, I wrote my own blog browsing the most is just myself.