ts-泛型

function echo<T>(arg:T):T{
  return arg
}

const result = echo("str")

function swap<T,U>(arr:[T,U]):[U,T]{
  return [arr[1],arr[0]]
}
const result1 = swap(["str",123])

interface IWidthLength{
  length:number;
}
function echoWidthLength<T extends IWidthLength>(arg:T):T{
  console.log(arg.length)
  return arg
}
const str = echoWidthLength("str")
const str1 = echoWidthLength({length:10})
const str2 = echoWidthLength([1,2,3])


class Queue<T> {
  private data =[];
  push(item:T){
    return this.data.push(item)
  }
  pop():T{
    return this.data.shift()
  }
}
const queue = new Queue<string>()
// queue.push(1)
queue.push("str")
console.log(queue.pop().length)

interface KeyPair<T,U> {
  key:T;
  value:U;
}
let kp1 : KeyPair<number,string> = {"key":123,value:"str"}

interface IPlus<T>{
  (a:T,b:T):T
}
function plus(a:number,b:number):number{
  return a+b
}
function connect(a:string,b:string):string{
  return a+b
}
const a :IPlus<number> = plus
const b :IPlus<string> = connect

  

上一篇:【Docker】Dockerfile 之 ARG(二)


下一篇:TypeScript泛型接口定义和使用