[Typescript] The use of generics and generic constraints in ts

The use of generics and generic constraints in Typescript

Generic understanding and definition

Generics are a special kind of variable that are only used to represent types rather than values, called: type variables.

When we define a variable of uncertain type, there are two solutions:

1.
There are problems when using any to define any: although you can know the type of the incoming value, you can’t get the type of the function’s return value; using too much any loses the advantage of ts type protection, and becomes the popular anyscript
2 , Using generics Generics mean that when defining a function/interface/type, the specific type is not specified in advance, and the specific type is determined when the method is called

Generic definition: it can support unspecific data types and require the parameters passed in and returned to be consistent

Popular understanding: Generic is to solve the reusability of classes, interfaces, methods , and support for unspecific data types

generic function

Using generics in functions

function getData<T>(val:T):T{
    
       //T不是定死的,可以改成任意字符串,但是3个地方要一致
        return val;
}
getData<number>(123)
getData<string>('zhendeshi')
getData<string | boolean>(true) //返回值是布尔类型的 true
//getData<string>(123)  这是错误的写法,泛型的定义是要求传入和返回的参数一致,此时传入参数不一致

generic class

Using generics in classes

//在类中实现挑选最小数
class Minlist<T> {
    
    
    list:T[]=[]
    add(value:T):void {
    
    
        this.list.push(value)
    }
    min():T {
    
    
        var minli = this.list[0]
        for(var i=0;i<this.list.length;i++) {
    
    
            if(minli>this.list[i]) {
    
    
                minli = this.list[i]
            }
        }
        return minli
    }
}
var m=new Minlist<number>() //实例化类,并且制定了类的T代表的类型是number
m.add(3)
m.add(2)
m.add(4)
console.log(m.min());//2
var m=new Minlist<string>() //实例化类,并且制定了类的T代表的类型是string
m.add('a')
m.add('p')
m.add('u')
console.log(m.min());//a

generic interface

Using generics in interfaces

Writing 1

interface Config{
    
    
    <T>(val:T):T
}
var getData:Config=function<T>(val:T):T{
    
    
    console.log(val);
    return val
}
getData<string>('zs')
// getData<number>('zs')  错误写法,只能传入number值

Writing 2

interface Config<T>{
    
    
    (val:T):T
}
function getData<T>(val:T):T{
    
    
    console.log(val);
    return val
}
var mygetdata:Config<string> = getData
mygetdata('200')

Generic constraints

Generic constraints are constraints on generic types. When using attributes or methods of generic parameters in functions, generic constraints need to be imposed . The student function shown below can accept any type you choose to pass into the type variable. However, in this case, you should limit the types that the value parameter can accept to a range of types to which you can perform addition operations, rather than accepting any possible type. This situation is called a "generic constraint".

Constrain Generics Using Interfaces

interface Person {
    
    
  name:string;
  age:number;
}
function student<T extends Person>(value:T):T {
    
    
  return value;
}

student({
    
    name:'lili'});//错误写法,类型 "{ name: string; }" 中缺少属性 "age",但类型 "Person" 中需要该属性
student({
    
     name: "lili" , age:'11'});//错误写法,不能将类型“string”分配给类型“number”
student({
    
     name: "lili" , age:11});

Guess you like

Origin blog.csdn.net/m0_63779088/article/details/126486541