[Typescript] ThisType

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.

 

posted @ 2022-11-08 02:34  Zhentiw  阅读(63)  评论(0编辑  收藏  举报