I'm making a library and users should be able to create a custom object that extends a TypeScript interface. This custom object is then passed to a library function that merges the custom object in an object with defaults and returns the result.
The custom object that extends the TypeScript interface can override methods from the interface. I want to set this
in the method to the custom object. Currently I have this (failing) code:
interface Thing<T extends SpecialThing = SpecialThing> {
a: number
derp(this: T, blah?: Partial<T>): T
}
interface SpecialThing extends Thing {
b: string
}
function createThing<T extends Thing<T>>(options: T) {
return Object.assign({
a: 1,
derp() {}
}, options)
}
// userland:
interface CustomThing extends SpecialThing {
c: boolean
}
createThing<CustomThing>({
a: 1,
b:'b',
c: true,
derp() {
this.c // `this` should be CustomThing
return this
}
})
See the TypeScript playground. SpecialThing
is the interface users can extend, Thing
is more used internally.
It would be ok to only have SpecialThing
, but I need the type variable T
to pass to derp(this: T)
and it seems silly to have users extend SpecialThing
like so:
interface CustomThing extends SpecialThing<CustomThing> {
c: boolean
}
this
for such behavior, but in your particular case, why do you need anything like that at all? What about this code doesn't meet your needs?derp
method. I've updated the example to show why (it needs it for another argument and a return value).this
work well enough for you, as in this code?this: this
toderp
's signature it worked. Didn't know about polymorphic this, thanks a lot. Also for the superfast replies 👍 You want to post an answer or shall I answer it myself?