当前位置:网站首页>Simple understanding and application of TS generics

Simple understanding and application of TS generics

2022-07-07 15:47:00 Sam young

What is generics

Simply speaking , Generic refers to a type in different places , There are different values , Listed below

function creatValue(a: string):string {
    
	return a;
}

function creatValueNumber(a: number):number {
    
	return a;
}

Or use any, But it will lose its use ts Type constraints of , Now you can solve this problem by using generics

function creatValue<T>(a: T):T {
    
	return a;
}

creatValue<string>("string")
/**  You can also directly pass in ellipsis <> */
creatValue("string")
...

Of course, it can also be made into multiple


function creatValue<T,X>(a: T,b:X):T {
    
  console.log(b)
	return a;
}


creatValue<string,number>("a",123)
//  perhaps 
creatValue("a",123)

Inherited usage of generics

/**  Define basic information */
interface base {
    
  name:string;
  age:number;
}
/**  Define a student type , Generic indeterminate types then inherit base */
interface student<T extends base> {
    
  baseInfo: T
}

/**  Here I customize the type I want  */
interface myBase extends base {
    
  address: string;
  grade:string
}

/**  Final type  */
const studentA: student<myBase> ={
    
  baseInfo: {
    
    name:' Zhang San ',
    age:14,
    address:' China ',
    grade:' The new moon '
  }
}

/**  Define another body type  */ 
interface bodyBase extends base {
    
  weight: string;
  height:string
}

const studentB: student<bodyBase> ={
    
  baseInfo: {
    
    name:' Zhang San ',
    age:14,
    weight:'70kg',
    height:'170cm'
  }
}

/**  Can also inherit all  */ 
interface AllBase extends bodyBase,myBase {
    }

const studentC: student<AllBase> ={
    
  baseInfo: {
    
    name:' Zhang San ',
    age:14,
    weight:'70kg',
    height:'170cm',
    address:' China ',
    grade:' The new moon '
  }
}

Hard core


interface base {
    
  name:string;
  age:number;
}

interface student<T extends base> extends baseInfo<T> {
    

  test(t: T):T;
}

interface baseInfo<T> {
    
  baseInfo: T
}

interface bodyInfo extends base {
    
  weight: string;
  height: string;
}

const studentA:student<bodyInfo> = {
    
  baseInfo:{
    
    name:' Zhang San ',
    age:18,
    weight:'70kg',
    height:'170'
  },
  test(t: bodyInfo): bodyInfo{
    
    return t
  }
}



function test<T extends bodyInfo>(option: baseInfo<T>){
    
  option.baseInfo.age = 1
}

原网站

版权声明
本文为[Sam young]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130610295218.html