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.
标签:Typescript,obj,double,ThisType,value,half,type From: https://www.cnblogs.com/Answer1215/p/16868035.html