typescript 中的 this 类型
转载:https://www.cnblogs.com/wjaaron/p/12974604.html
typescript中,this 也是一种类型,一个计算器的例子:
class Counter{
constructor(public count:number = 0){}
add(value:number){
this.count += value
return this
}
subtract(value:number){
this.count -= value
return this
}
}
let counter = new Counter(10)
console.log(counter.count) // 10
counter.add(2).subtract(3)
console.log(counter.count) // 9
这里 this 指的是实例对象,每个方法都返回 this 类型时,我们就可以通过链式调用的形式来使用这些方法。
上面的类使用了 this 类型,你可以继承它,新的类可以直接使用之前的方法,不需要做任何的改变。
class PowerCounter extends Counter{
constructor(public count:number){
super(count)
}
pow(value:number){
this.count = this.count ** value
return this
}
}
let powcounter = new PowerCounter(2)
powcounter
.pow(3)
.add(3)
.subtract(1)
console.log(powcounter.count) // 10
PowerCounter 继承了 Counter,本身只定义了 pow 这个实例方法,但是因为返回了 this 类型,所以可以使用父类中的方法。
在对象中,属性值可以是一个函数,函数内访问 this,默认情况下是对这个对象的引用,this 类型也就是这个对象的字面量类型:
const info = {
name:'Tom',
getName(){
return this.name // Tom 这里的 this 类型是 {name:string, getName():string}
}
}
如果显式指定了 this 类型,那么 this 的类型就改变了:
const info = {
name:'Tom',
getName(this:{age:number}){
this // 这里的 this 类型就是 {age: number}
}
}


浙公网安备 33010602011771号