为TS中的this进行类型注释

436 阅读1分钟

TS中的函数与this

  • TS 中默认情况下如果没有指定 this 的类型,this 是 any 类型
    直接使用的话,会有错误提示 "this" 隐式具有类型 "any",因为它没有类型注释。

我们可以用下面这种方式解决,在函数第一个参数声明 this 的类型,函数调用传入的参数从第二个开始接收

//如果明确this类型,可以在此指定
function hello(this:any,msg:string):void{
  console.log(`${this.name} say:${msg}`);
}

const dog = {
  name:'jack',
  hello
}

dog.hello('good night')

编译后代码如下

function hello(msg:string){
  console.log(`${this.name} say:${msg}`);
}

const dog = {
  name:'jack',
  hello
}

dog.hello('good night')