2

I have a class with a static method that returns the instance of this class (a second constructor):


class Node1Model {
  attr1?: string
  attr2?: string

  static fromJsonObj(jsonObj: Node1Json): Node1Model {
    const model = new Node1Model();
    // some extra logic
    model.attr1 = jsonObj.attr1;
    model.attr2 = jsonObj.attr2;
    return model;
  }

}

And I have a bunch of different classes that follow the same pattern: they all have alternative constructors fromJsonObj.

How do I create an abstract class for them?

Specifically, how do I specify that a static method on the class should return the instance of the same class? Like so:


abstract class BaseModel<J> {
  static fromJsonObj(jsonObj: J): <WHAT TO PUT HERE?> {
    throw new Error('not implemented');
  }
}

Update

As suggested here , I tried the following:


class BaseModel {
  static fromJsonObj<T extends typeof BaseModel>(jsonObj: any): InstanceType<T> {
    throw new Error('not implemented');
  }
}

class Node1Model extends BaseModel {
  attr1?: string
  attr2?: string


  static fromJsonObj(jsonObj: any): Node1Model {
    const model = new Node1Model();
    // some extra logic
    model.attr1 = jsonObj.attr1;
    model.attr2 = jsonObj.attr2;
    return model;
  }
}



but this results in the following error:

TS2417: Class static side 'typeof Node1Model' incorrectly extends base class static side 'typeof BaseModel'.
  The types returned by 'fromJsonObj(...)' are incompatible between these types.
    Type 'Node1Model' is not assignable to type 'InstanceType<T>'.

3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.