Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Typescript - Trying to call method on abstract base with derived type as parameter

The abstract base has a method that takes a base/derived and performs something on it. Seems like I'm missing something with the typing, trying to find out what.

Attempt 1:

abstract class Base {
  protected runFuncOnThis = (func: (baseOrDerived: Base) => void) => {
    func(this);
  };
}

class Derived extends Base {
  public doIt = () => {
    this.runFuncOnThis((derived: Derived) => { // ERROR HERE
      console.log(derived);
    });
  };
}

Error: Argument of type '(derived: Derived) => void' is not assignable to parameter of type '(baseOrDerived: Base) => void'. Types of parameters 'derived' and 'baseOrDerived' are incompatible. Property 'doIt' is missing in type 'Base' but required in type 'Derived'.ts(2345)

Attempt 2:

abstract class Base2 {
  protected runFuncOnThis = <T extends Base2>(func: (baseOrDerived: T) => void) => {
    func(this); // ERROR HERE
  };
}

class Derived2 extends Base2 {
  public doIt = () => {
    this.runFuncOnThis((derived: Derived2) => {
      console.log(derived);
    });
  };
}

Error: Argument of type 'this' is not assignable to parameter of type 'T'. 'this' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Base2'.ts(2345)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

playground

Since you're using this in an arrow function, it means this is the current context (Base) meanwhile func wants Derived as its argument. Change the method type to a normal function (that has its own context) and define this as T extends Base to satisfy func's argument.

abstract class Base {
  protected runFuncOnThis<T extends Base>(this: T, func: (baseOrDerived: T) => void) {
    func(this);
  };
}

class Derived extends Base {
  public doIt = () => {
    this.runFuncOnThis((derived) => {
      console.log(derived);
    });
  };
}

class Derived2 extends Base {
  public doIt = () => {
    this.runFuncOnThis((derived) => {
      console.log(derived);
    });
  };
  public someProperty = 123;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!