为了账号安全,请及时绑定邮箱和手机立即绑定

【备战春招】第4天 泛型

标签:
JavaScript

课程名称GO开发工程师

课程章节:6-5:泛型

课程讲师ccmouse

课程内容

大纲:
图片描述

  1. 示例泛型:
    约束数组元素、Promise返回值

    自定义泛型的类/函数、自动推导 、显示指定
    图片描述
    代码示例:
const a: Array<string> = []
a.push('123')

const p = new Promise<string>((resolve, reject) => {
   resolve('123')
})

// 自定义泛型的类或函数
class MyArray<T> {
   data: T[] = []
   add(t: T) {
       this.data.push(t)
   }
   // 泛型函数
   map<U>(f: (v: T) => U) :U[] {
       return this.data.map(f)
   }
   print() {
       console.log(this.data)
   }
}

// 自动推导
const b = new MyArray()
b.add(123) // const b: MyArray<unknown>
b.print()
// 'v' is of type 'unknown'
//b.map(v => v.toExponential()) // 自动推导失败

// 显示指定
const b1 = new MyArray<number>()
b1.add(123) // const b1: MyArray<number>
b1.print()
// 使用泛型函数
// 自动推导结果:(method) MyArray<number>.map<string>(f: (v: number) => string): string[]
b1.map(v => v.toExponential())
// 显示指定
b1.map<string>(v => v.toExponential()) // toExponential()返回string

interface HasWeight {
   weight: number
}
class MyArray2<T extends HasWeight> {
   data: T[] = []
   add(t: T) {
       this.data.push(t)
   }
   sortByWeight() {
       this.data.sort((a, b) => a.weight - b.weight)
   }
}
class WeightNumber {
   constructor(public weight:number) {}
}

const b3 = new MyArray2<WeightNumber>()
b3.add(new WeightNumber(145))
b3.add(new WeightNumber(12))
b3.add(new WeightNumber(123))
b3.sortByWeight()
console.log(b3)

课程收获
利用接口来约束泛型的参数
定义泛型函数
尽量使用编译器的自动推导

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消