Get Off My Lawn Get Off My Lawn - 1 month ago 9
TypeScript Question

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?

Answer

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.