Q:

Type 'this' is not assignable to type 'T'

I have the following class:
class MyClass {

    public each<T extends MyClass>(callback: (item: T) => void): T {
        /* Loop through an array and apply the callback */
        return this;
    }

}

class MyClass2 extends MyClass {

    public before(html: string): MyClass2 {
        return this.each<MyClass2>(item => { /* Do Some Stuff */ });
    }

}

I am then getting this error:

[ts] Type 'this' is not assignable to type 'T'.

How can I return the class instance?

A:

To return the instance of MyClass you need to change the return type to MyClass 
public each<T extends MyClass>(callback: (item: T) => void): MyClass {
    /* Loop through an array and apply the callback */
    return this;
}

A:

You can use this type to represent that each returns the instance of the same type for which it was called:
class MyClass {

    public each<T extends MyClass>(callback: (item: T) => void): this {
        /* Loop through an array and apply the callback */
        return this;
    }

}

class Derived extends MyClass {
    foo: string;
}

let derived = new Derived;

derived = derived.each(() => {});

Note that this type is not the same as T - T is a type for array items, it may or may not be the same as the instance type for which you are calling each method.

