本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
这是typescript学习的系列课程,今天开启typescript的第6篇。
不多说废话,直接精简出最精华的部分给大家。
如果有朋友对于typescript的基础不是很了解的话,欢迎点击下面两篇文章跳转进行学习。
接前面两篇:
- Typescript基础一,这一篇介绍了如何执行typescript文件,以及类型注解的例子。
- Typescript基础二,这一篇介绍了typescript在函数中的一些基础使用。
- Typescript基础三,这一篇介绍了typescript联合类型的相关知识点。
- Typescript基础四,这一篇介绍了typescript交叉类型、类型断言、字面量类型等知识。
- Typescript基础五,这一篇介绍了typescript函数基础知识的分享。
- Typescript基础六,这一篇介绍了typescript函数中构造签名以及参数的基本使用。
我们接着函数模块的知识,今天是它的终极版。
函数的重载
现在我们需要实现这样一个需求,就是实现两个数字或者两个字符串之间的相加。我所知道的有两种方案可以实现。
- 方案一
通过编写两个函数的方式进行实现,一般
不推荐这种方案。
function add1(num1: number, num2: number) {
return num1 + num2
}
function add2(str1: string, str2: string) {
return str1 + str2
}
const numresult1 = add1(10, 20)
const numresult2 = add2("abc", "cba")
console.log('numresult1>>>', numresult1);
console.log('numresult2>>>', numresult2);
- 方案二 通过TS函数的重载实现。
一共分成两步。
1、先编写重载的签名,目的是定义当前的参数类型,比如下面的例子中就是限定了参数是number类型和string类型,返回值也分别是number和string类型。
2、编写函数实现的具体逻辑。
// 1.先编写重载签名
function add(arg1: number, arg2: number): number
function add(arg1: string, arg2: string): string
// 2.编写通用的函数实现
function add(arg1: any, arg2: any): any {
return arg1 + arg2
}
const numresult3 = add(10, 20)
const numresult4 = add("aaa", "bbb")
console.log('numresult3>>>', numresult3);
console.log('numresult4>>>', numresult4);
- 方案三 使用联合类型进行实现。这里的string类型跟any[]类型都有length属性,所以不会报错。
function getLength(arg: string | any[]) {
return arg.length
}
- 方案四 使用对象类型的实现方式,强制该参数拥有length属性。这种方式比较灵活,可以满足多种条件。
function getLength(arg: { length: number }) {
return arg.length
}
使用的优先级。 能用联合类型的方式实现就先用联合类型,不能使用联合类型的方式就用函数的重载。
this的指向
this在ts中默认是any类型。
所以我们在项目中如果要给this指定类型的时候,一般可以通过tsc --init创建tsconfig.json,我们可以看到有这样一个配置"noImplicitThis": true,,配置的作用是
不允许不明确类型的this。
这样我们在明确this的配置时,可以这样设置
function foo(this: { name: string }, info: {name: string}) {
console.log(this, info)
}
foo.call({ name: "why" }, { name: "kobe" })
这里强制给this的指向配置一个类型。
还有一种方式,可以通过设置ThisType的方式给this强制绑定某个类型。
// 1. 定义接口IState
interface IState {
name: string
age: number
}
// 2. 给接口创建属性约束
interface IStore {
state: IState
eating: () => void
running: () => void
}
// 3. 定义数据,并且通过ThisType将对象store的this的类型设置为IState
const store: IStore & ThisType<IState> = {
state: {
name: "why",
age: 18
},
eating: function() {
console.log(this.name)
},
running: function() {
console.log(this.name)
}
}
ok,以上为今天对于函数的重载以及this指向的讲解。
学如逆水行舟,不进则退。不求贪多,只求稳步的进步。