TypeScript-进阶(六)-ts中的this

41 阅读1分钟

配置

在js中,this的不同调用方式会导致this的指向不同,所以在ts中,this可能会出现隐式any的推导。
可以通过配置noImplicitThis禁止隐式any的this

{
  "compilerOptions": {
    "noImplicitThis": true, // 不允许this隐式的指向any
  },
}

声明this指向

在TS中,允许在书写函数时,手动声明该函数中this的指向,将this作为函数的第一个参数,该参数只用于约束this,并不是真正的参数,也不会出现在编译结果中

type Test = {
    name: string
    // 第一个参数为this的指向
    sayHi: (this: Test, n: number) => void
}

const obj: Test = {
    name: '张三',
    sayHi: (n) => {
        console.log(n);
    }
}
obj.sayHi(2)