Typescript derive return type from inherited method

Viewed 36

Let's say we have WrapperClass

export abstract class WrapperClass {
  protected abstract childMethod(): unknown;

  wrapperMethod(): unknown {
    const result = this.childMethod();
    return result;
  }
}

ChildClass

export class ChildClass extends WrapperClass {
  protected childMethod(): ChildResponse {
    const response = new ChildResponse();
    return response;
  }
}

I want typescript to automatically determine that response is of type ChildResponse when I do this:

const childClass = new ChildClass();
const response = childClass.wrapperMethod();
console.log(response.id);
1 Answers

You can use a generic type parameter when defining the wrapper class, so that every child class would be required to define a return type for the child method:

export abstract class WrapperClass<ChildResponseType> {
  protected abstract childMethod(): ChildResponseType;

  wrapperMethod(): ChildResponseType {
    const result = this.childMethod();
    return result;
  }
}

Then pass the response type when defining the child class:

export class ChildClass extends WrapperClass<ChildResponse> {
  protected childMethod() {
    const response = new ChildResponse();
    return response;
  }
}

See this link for a Typescript sandbox with an example.

Related