TS-下篇: TS_this内置工具

129 阅读1分钟

ThisParameterType

获取函数中this参数的类型

function foo(this: { name: string }, desc: { name: string }) {
  console.log(this, desc)
}
type fooType = typeof foo
type thisFooType = ThisParameterType<fooType>

OmitThisParameter

去除函数中this参数的类型

function foo(this: { name: string }, desc: { name: string }) {
  console.log(this, desc)
}
type fooType = typeof foo
type thisFooType = ThisParameterType<fooType>

ThisType

用于绑定一个上下文的this

开始this指向Iperson, 当使用联合类型搭配ThisType变为 Iperson & ThisType后this就绑定了ThisType中的Ifriend, 而Ifriend类型中有name可以直接访问

interface Ifriend {
    name: string
    age: number
  }
interface Iperson {
  friend: Ifriend
  eating: () => void
}
const person: Iperson & ThisType<Ifriend> = {
  friend: {
    name: "messi",
    age: 33
  },
  eating: function() {
    console.log(this.name)
    }
  }