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

【九月打卡】第5天 TypeScript学习 9-28章

标签:
征文 活动

课程名称: 晋级TypeScript高手,成为抢手的前端开发人才

课程章节: 9-28 【扩展: 为第11章手写 Promise 源码铺路】:从回调函数讲起【本节赠送,会的略过】

课程讲师: keviny79

课程内容:
本章节是复习 函数参数和回调函数,为第11章手写 Promise 源码铺路。

定义函数类型:

// (text:string) 函数变量
//  => string 函数返回值类型
type FuncType = (xxx:string) => string

使用定义的函数类型:

type FuncType1 = (one: number, two: string) => string

// 1-1 定义函数变量
//  1-2 右边的函数需要符合 定义的函数‘类型( FuncType1 )’
let func: FuncType1 = function (one: number, two: string): string {
  return "sss";
};

//-----------------------------

// 1-3 对上面的写法做一个改变
let func2: FuncType1 = function (one: number): string {
  console.log(one)
  return "sss";
};

// 理解:
// 上面少写一个函数参数,也是可行的。
// 为什么可以?这里可以理解为和继承一样,
// 多个参数不能继承少个参数,如下
type FunTestType1 = (one: number, two: string) => string
type FunTestType2 = (one: number) => string
// 这里返回 never
type beginType1 = FunTestType1  extends FunTestType2  ? FunTestType1 : never

// 少的参数可以继承多的参数,如下
// 这里返回 FunTestType2 
type beginType2 = FunTestType2  extends FunTestType1  ? FunTestType2  : never

// 所以 1-3 那理解为,右边 函数 继承 FuncType1定义的函数类型。
// 因为定义的函数类型,变量比声明的函数变量多,所以 1-3 没有报错

//-----------------------------

// 使用 1-3 声明的函数
// 这里需要传递两个参数,
// 因为这里你给这个函数变量约束为 FuncType1 函数类型,
// 所以要符合这个声明的函数,而这个函数类型是有两个变量的,这里就需要传递两个参数
// 如果你不给这个 函数变量 添加约束也就是 let func2 = (xx:number):string => {return ''},这样就会根据 = 右侧的函数自动推到 func2 的函数类型
// 当然在 函数体中只能输出一个 函数参数,因为你函数体只写了一个函数参数
func2(123, 'abc')

回调函数:

type FuncType1 = (one: number, two: string) => string

// 定义一个函数,函数中 func 参数的类型是 FuncType1,FuncType1是一个函数
// 所以 func 需要传递,符合 FuncType1 类型的 函数
function testFun(func: FuncType1 ) {
	// 调用外部传递的函数,
	// 这里调用需要符合 FuncType1 函数类型 的规则
	func(12, "abc")	// 回调函数
}

// 这里调用定义的函数,
// 传递的函数也是符合 FuncType1 类型的。
// 传递一个参数为什么符合,你可以看 s100 代码
testFun(function (one: number):string {
  console.log(one)
  return "sss";
})

// s100 代码
function testFun(
	func: FuncType1 = function (one: number):string {
	  console.log(one)
	  return "sss";
	} 
) {
	func(12, "abc")
}

课程收获:
本节对函数类型声明和使用时参数的变化,有了清晰的理解

图片描述

点击查看更多内容
TA 点赞

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

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
10
获赞与收藏
5

关注作者,订阅最新文章

阅读免费教程

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

100积分直接送

付费专栏免费学

大额优惠券免费领

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

举报

0/150
提交
取消