TypeScript: Return instance of class from an interface method

Viewed 457

How can I specify the return type of an interface method to be an instance of the class implementing the interface in TypeScript? For example:

interface Entity {
  save: () => ClassThatImplementsEntity
}

so that a class implementing Entity interface will have a save method that returns instance of that class

class User implements Entity {
  save() {
    // some logic
    return this;
  }
}
1 Answers

Usually your interface should not know about the implementation, but if save() should return exactly the type of class you can use this

interface Entity {
  save: () => this
}

class E1 implements Entity {
    save() {
        return this
    }
}

class E2 extends E1 {

}
const e1 = new E1()
const e2 = new E2()
const x1 = e1.save() // type of x1 is E1
const x2 = e2.save() // type of x is E2

It looks like it is something you need

Related