[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.
相关文章
- [Typescript] 137. Hard - Discriminated union to Object
- [Typescript] 81. Medium - Number Range
- [!Typescript] Tips: dynamic specify the type of arguments to function
- [Typescript] 55. Medium - Reverse
- [Typescript] 49. Medium - PartialByKeys
- [Typescript] Tuple type usage example & Discriminated Unions
- [TypeScript] Function Overloads in Typescript
- [Typescript] 135. Easy - Maybe helper
- [Typescript] getProp<T, P extends PathKeys<T>>(obj: T, path: P): PropType<T, P>
- [Typescript] 118. Hard - IsRequiredKey
- [Typescript] “Partial” Mapped Type
- [Typescript] Typescript Enums vs Booleans when Handling State
- TypeScript 里 never 类型的用法举例