'Taking and returning structures of `this` type inside class methods
What is the correct writing way of this class?
class X {
f(): this {
return this;
}
g(): { a: this } {
return { a: this };
}
h(obj: {a: this}): this {
return obj.a;
}
}
In the ts playground, it keeps saying:
A 'this' type is available only in a non-static member of a class or interface.
Now, I could just use X as the type, but I want these methods to also infer the correct type when X is extending another parent class AND when another child class is extending X.
Solution 1:[1]
Based on this thread: https://github.com/microsoft/TypeScript/issues/5863
It appears, this is the same problem as polymorphic this in static methods, even though the methods are instance methods.
So from that inspiration, it appears this works...
g<T extends this>(this: T): { a: T } {
return {a: this};
}
Solution 2:[2]
Typing the methods with generics and letting this be anything would be one approach.
class X {
f(): this {
return this;
}
g<T extends unknown>(this: T): { a: T } {
return { a: this };
}
h<T extends unknown>(obj: {a: T}): T {
return obj.a;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CMCDragonkai |
| Solution 2 | CertainPerformance |
