CMCDragonkai
CMCDragonkai

Reputation: 6372

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.

Upvotes: 1

Views: 38

Answers (2)

CMCDragonkai
CMCDragonkai

Reputation: 6372

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};
  }

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370679

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;
    }
}

Upvotes: 0

Related Questions