Currently, I am in the process of creating a generic base class for a Protractor page object. This particular class is designed to be exceptionally generic, featuring an init method that will return itself after either waiting or not waiting for angular, based on whether the object is Angular or not. My intention with the init method is to return the correct type - the class that extends the base class. However, I have encountered a compile error which states that I cannot return 'this' because it is not an instance of the generic parameter.
export abstract class AbstractLoadable<T extends AbstractLoadable<T>> {
protected isAngularComponent: boolean;
public constructor(isAngularComponent: boolean = true) {
this.isAngularComponent = isAngularComponent;
}
public initComponent(): T {
browser.waitForAngularEnabled(this.isAngularComponent);
if(this.isAngularComponent) {
browser.waitForAngular();
}
return this as T; // Error occurs here.
}
}
The error message reads: Type 'this
' cannot be converted to type 'T
'. Type 'AbstractLoadable<T>
' is not comparable to type 'T
'.
This approach has proven successful in Java, but being relatively new to JavaScript and Typescript, I'm unsure if it can be achieved in Typescript. Any guidance would be greatly appreciated!