zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] ThisType

2023-09-14 08:59:11 时间

This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. Note that the noImplicitThis flag must be enabled to use this utility.

type Math = {
  double(): void,
  half(): void
}

const math:Math = {
  double(this: {value: number}) { // we have to tell what this is
    this.value *= 2
  },
  half(this: {value: number}) { // we have to tell what this is
    this.value /= 2
  }
}

const obj = {
  value: 1,
  ...math
}

obj.double()
console.log(obj.value)

obj.half()
console.log(obj.value)

 

We don't actually want to write this: {value: number}again and again.

 

So what we can do:

const math: Math & ThisType<{value: number}> = {
  double() {
    this.value *= 2
  },
  half() {
    this.value /= 2
  }
}

 

Two appraoch are the same, just by using Typescript utilites type ThisType<>, can simply our code.