current position:Home>Generics of typescript

Generics of typescript

2021-08-27 04:56:12 webInRun

This is my participation 8 The fourth of the yuegengwen challenge 6 God , Check out the activity details : 8 Yuegengwen challenge

Why use generics

  1. The definition limits the type
    function echo(arg:number):number{
        return arg
    }
     Copy code 
    You can only import number type , Unable to transfer in string Other types
    const result = echo(2)
     Copy code 
  2. use any
    function echo(arg:any):any{
        return any
    }
     Copy code 
    Yes, you can pass in any type , The types that can be passed in and returned can be inconsistent . For example, let's enter a number type , We only know that any type of value can return

Generic

Definition

Defining functions in , Interface or class , No specific type is specified in advance , Instead, it dynamically fills in the determined type value when using

Use

After the function name, add , among T It can be changed to any character .T Help capture incoming types ( such as number), Then we can use this type in parameters and return values T, This achieves the effect that the incoming type is consistent with the return type
Example 1:

function echo<T>(arg:T):T{
    return any
}
const result = echo(123)
 Copy code 

Example 2

function swap<T,U>(tuple:[T,U]):[U,T]{
  return [tuple[1],tuple[0]]
}
const s = swap(["23",23])
 Copy code 

Constraint generics

Why are there constrained generics

function echoWithLen<T>(arg:T):T{
    console.info(arg.length) // Error: T doesn't have .length
    return arg;
}
 Copy code 

The reason for the error is :T For any type , So people who use this function may pass in boolean type , and boolean The type is none length Attribute
Change to :

function echoWithArr<T>(arg:T[]):T[]{
    console.info(arg.length) 
    return arg;
}
const arr = echoWithArr([1,2,3])
const arr2 = echoWithArr([1,2,"3"]) //T Turned into number|string
// const arr3 = echoWithArr('str') //string In fact, there are length attribute , But will report a mistake , So there's a problem with this definition 
 Copy code 

use interface extends

interface IWithLength {
  length:number
}
function echoWithArr2<T extends IWithLength>(arg:T):T {
  return arg
}
const arrWith = echoWithArr2([1,2,3])
const arrWith2 = echoWithArr2('str')
// const arrWith3 = echoWithArr2(23) // Can not be , because number No, length attribute 
 Copy code 

The use of generics on objects

interface KeyPair<T,U> {
  key:T,
  value:U
}
let kp1:KeyPair<number,string> = {key:23,value:"23"}
let kp2:KeyPair<string,number> = {key:"23",value:23}
 Copy code 

Array< type > That's how it works

let n:number[] = [2,3,4]
let n2:Array<number> = [2,3,4]
 Copy code 

The use of generics on functions

interface IPlus2<T> {
  (a:T,b:T):T
}
function plus2(a:number,b:number) :number {
  return a+b;
}
function connect(a:string,b:string) :string {
  return a+b;
}
const p2:IPlus2<number> = plus2
const c2:IPlus2<string> = connect
 Copy code 

The use of generics on classes

Don't use typescript

class Queue {
  private data = []
  push(item) {
    return this.data.push(item)
  }
  pop(){
    return this.data.shift()
  }
}
const queue = new Queue()
queue.push(1)
queue.push("str")
console.info(queue.pop().toFixed())
// console.info(queue.pop().toFixed()) // Error will be reported at runtime 
 Copy code 

Use typescript Basic type checking

class Queue {
  private data = []
  push(item:number) {
    return this.data.push(item)
  }
  pop():number{
    return this.data.shift()
  }
}
const queue = new Queue()
queue.push(1)
// queue.push("str") // Will report a mistake , It's limiting 
console.info(queue.pop().toFixed())
 Copy code 

Use generic classes

The above function allows only incoming number type , But if you want to get a string that allows you to add , You have to redefine a class , It's not reasonable

class Queue<T> { 
  private data = []
  push(item:T) {
    return this.data.push(item)
  }
  pop():T{
    return this.data.shift()
  }
}
const queue = new Queue<number>()
queue.push(3)
console.info(queue.pop().toFixed()) //3
const queueStr = new Queue<string>()
queueStr.push("3")
console.info(queueStr.pop().indexOf("3")) //0
 Copy code 

copyright notice
author[webInRun],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827045609355g.html

Random recommended