Generic

When defining a function 、 Interface or class , Do not specify specific types in advance , When used, a specific type of feature is specified .

introduce

Let's create a function , Realization function : According to the specified quantity count And data value , Create a containing count individual value Array of Without generics , This function might look like this :

function createArray(value: any, count: number): any[] {
const arr: any[] = []
for (let index=0; index < count; index++) {
arr.push(value)
}
return arr
} const arr1 = createArray('a', 3)
const arr2 = createArray(1, 3)
console.log(arr1)
console.log(arr2)
console.log(arr1[0].toFixed(), arr2[0].split(''))

We created a function createArray, Pass in 2 Parameters value and count, return any An array of types , And then define a any Empty array of type arr. Next, let's look at the results



In the compilation phase, we did not report an error because , We put value Set up in order to any type , But when the compilation is finished, it runs ,arr1 Is string , String is none toFixed Methodical , So there's an error , Then we hope to report an error at the compilation stage , You can use generics

Use generics

//  Use function generics 
function createArray<T>(value: T, count: number): T[] {
const arr: Array<T> = []
for (let index=0; index < count; index++) {
arr.push(value)
}
return arr
}
const arr1 = createArray<number>(11, 3)
console.log(arr1[0].toFixed())
const arr2 = createArray<string>('AA', 3)
console.log(arr2[0].split(''))
console.log('---------')
console.log(arr2[0].toFixed()) // Report errors , Because the string doesn't have toFixed Method
console.log(arr1[0].split('')) // Report errors , because number No, split Method

Generic means that the type is determined by the user , such as function createArray<T>(value: T, count: number): T[], function createArray and value Parameters and return types are determined by the user .

const arr1 = createArray<number>(11, 3) This code is no problem , Because it stipulates number type , It's also coming in number

 

When we change the code to the following code :



We found that the report was wrong , Because it stipulates number type , The string is passed in 11,



When we enter the following code , You will also report mistakes.



The reasons are as follows



So if we use generics , You can avoid typing the wrong type or using the wrong method

Functions with multiple generic parameters

A function can define multiple generic parameters

function swap <K, V> (a: K, b: V): [K, V] {
return [a, b]
}
const result = swap<string, number>('abc', 123)
console.log(result[0].length, result[1].toFixed())

Generic interface

interface IbaseCRUD <T> {
// Define generic arrays data
data: T[]
add: (t: T) => void
getById: (id: number) => T
} class User {
id?: number;
name: string;
age: number; constructor(name, age) {
this.name = name;
this.age = age;
}
} class UserCRUD implements IbaseCRUD<User> {
data: User[] = [] add(user: User): void {
user = {...user, id: Date.now()}
this.data.push(user)
console.log(' preservation user', user.id)
} getById(id: number): User {
return this.data.find(item => item.id === id)
}
} const userCRUD = new UserCRUD()
userCRUD.add(new User('tom', 12))
userCRUD.add(new User('tom2', 13))
console.log(userCRUD.data)

Generic classes

Generic classes look like generic interfaces . Generic classes use ( <>) Include generic types , After the class name .

class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
} let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

GenericNumber The use of classes is very intuitive , And you may have noticed , There's nothing to limit it to just using number type . You can also use strings or other more complex types .

let stringNumeric = new GenericNumber<string>();
stringNumeric.zeroValue = "";
stringNumeric.add = function(x, y) { return x + y; }; console.log(stringNumeric.add(stringNumeric.zeroValue, "test"));

Like interfaces , Put generic types directly after classes , It can help us confirm that all properties of a class are using the same type .

Generic constraint

If we take a generic parameter directly length attribute , Will report a mistake , Because the generic doesn't know it has this attribute at all

//  No generic constraints 
function fn <T>(x: T): void {
console.log(x.length) // Report errors , Because I don't know x What type is it
}

We can use generic constraints to implement

interface Lengthwise {
length: number;
} // Specify generic constraints
function fn2 <T extends Lengthwise>(x: T): void {
console.log(x.length)
}

We need to pass in values that match the constraint type , Must include length attribute :

fn2('abc')
// fn2(123) // error number No, length attribute

TypeScript(7) More articles on generics

  1. TypeScript Sketch - Generic 、 enumeration

    /* Generic , Features with many benefits . But I'm not going to say the most basic thing here , Just going to say something and C# Different places */ /* Generic interface GenericIdentityFn The description of the method is defined identity The method is its implementation ...

  2. TypeScript Generics( Generic )

    A major part of software engineering is building components , Built components need not only to have clear definitions and unified interfaces , It also requires that components be reusable . Components that support existing data types and data types to be added in the future provide good flexibility for the development process of large software systems . stay C# and ...

  3. TypeScript introduction - Generic

    Generic To create a reusable component , The data type must be compatible with many types , So how to be compatible ,TypeScript Provides a great way to : Generic Hello World To be compatible with multiple data formats , Someone might think of any, namely ...

  4. TypeScript And Generic

    https://m.runoob.com/manual/gitbook/TypeScript/_book/doc/handbook/Generics.html Generic : It can support multiple types of data Of generic functions ...

  5. React + TypeScript Implement generic components

    The generic type TypeScript in , type (interface, type) Can be declared as generic , It's very common . interface Props<T> { content: T; } This shows that Pr ...

  6. typescript interface Generic

    interface interface Obj { [index: string]: any; } class Person { name: string; } let obj: obj = { na ...

  7. TypeScript Generics of

    What is generics , What's the usage? ? Generics literally mean a wide range of types , How to be extensive ? Of course, it can change the most widely , The so-called generics are the variable writing of types , Make your variable type dynamically variable , Application scenarios such as examples described in official documents : A function , Enter what ...

  8. TypeScript Introduction 6 :TypeScript The generic

    Generic functions Generic classes One . Generic functions Before generic functions , Let's briefly describe generics , Defining a variable as a generic type allows you to determine its type when you use it . What does that mean ? Let's say we have a function , There may be many cases of parameters and return values , Only when calling ...

  9. typescript - 6. Generic

    Generic classes class MinClas<T>{ public list:T[]=[]; add(value:T):void{ this.list.push(value); } min():T{ ...

  10. Reprint :《TypeScript Introduction to Chinese 》 9、 Generic

    Copyright Article reprinted from :https://github.com/zhongsp It is recommended that you jump to the website above to see the latest version . Introduce In Software Engineering , We don't just have to create consistent, well-defined API, Also consider reusability . Component not ...

Random recommendation

  1. Leetcode#73 Set Matrix Zeroes

    Original address Use the first row and the first column of the rectangle as mask Code : void setZeroes(vector<vector<int> > &matrix) { ].empty()) ...

  2. BroadcastReceiver Learning notes

    1. Register in code with AndroiManifest.xml The difference between registration (a) Registering in code can control the time of registration and logout . For example onCreate-onDestory, onStart-onStop, onRes ...

  3. [CodeForce]358D Dima and Hares

    Yes N<3000 I have a pet to feed , Only one at a time , Feed each pet , Pet satisfaction depends on : 1 The two neighbors next to each other didn't feed ,a[i] 2 One of the neighbors fed it ,b[i] 3 Both neighbors have fed it ,c[i] Feed all the pets to one ...

  4. STL Medium Traits Programming techniques

    I've been reading <STL Source analysis >, notice Traits In the programming techniques section , I can't help feeling STL The innovative ability of the source code author . So what is Traits Programming techniques ? And listen to me : We know that many operations of the container are expanded through iterators ...

  5. Competitive advertising system - Logistic regression optimization method -L-BFGS

    Logistic regression optimization method -L-BFGS The optimization method of logistic regression is a classic problem , If we think of it as a maximum entropy model , So we know that the earliest optimization method is IIS, I will not elaborate on this method , Because it's very slow . It turns out that in the field of optimization ...

  6. mybatis Configure multiple data source transactions (Transaction) Handle

    When mybatis When there is only one data source in the configuration file , In the normal form of transaction annotations @Transaction There is no problem , But when there are multiple data sources in the configuration file, it is found that the transaction does not work , How to solve this problem ? Look at the following case :

  7. BZOJ 3105: [cqoi2013] new Nim game [ Gauss elimination XOR Linear base ]

    I will also use the portal in the future ! The question : Some numbers , Select an XOR and no with the largest weight 0 Set Finally, I understand what a linear basis is ... We'll sort it out later Find a linear unrelated subset with the largest weight Linear unrelated subsets satisfy the properties of matroids , Greedily choose the one with the largest weight , Using height ...

  8. js Commonly used API Method

    String Objects are commonly used API:API Application programming interface , It's actually some pre-set methods . charAt() Method to return the characters in the specified position . stringObject.charAt(index) index ...

  9. HackerRank-Python The siege process -2.List comprehensions

    if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) print ...

  10. 【 aggregate 】Java Collections framework

    Java Class library helps us realize the traditional data structure in programming . This article skips the theory part , This paper mainly introduces how to use the collection class in the standard library . 1 Separate the interface of the collection from the implementation Java The collection class library separates the interface from the implementation . Take the queue, for example : public ...