Introduction and use of generics in typescript

The main function of generics, when defining a function or class, if the type is not clear, you can use generics

For example, define a generic function, K is taken arbitrarily

function fn<K>(a:K) :K{
    
    
	  return a;
	}

Can directly call generic functions

fn(10); 

不指定泛型,TS自动对类型进行推断,意味着K的类型为number,参数a的类型为number,返回值的类型也为number
fn<string>('hello')

指定泛型为string

When multiple generics

function fn2<T,K>(a:T,b:K):T{
    
    
  console.log(b);
  return a;
}
//最好写上<number,string>
fn2<number,string>(123,'hello')

If you limit the scope of generics

interface Inter{
    
    
  length:number
}

//T extends Inter表示泛型T必须是Inter实现类(子类)
function fn3<T extends Inter>(a:T):number{
    
    
   return a.length
}

transfer

fn3('123')  //字符串有length长度
fn3({
    
    })  //报错

Guess you like

Origin blog.csdn.net/weixin_45389051/article/details/115285376
Recommended