Home > OS >  Taking and returning structures of `this` type inside class methods
Taking and returning structures of `this` type inside class methods

Time:05-07

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.

CodePudding user response:

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

CodePudding user response:

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