TypeScript: return type of self-regulation for methods in inheriting classes

Disclaimer: I find it difficult to summarize the problem in the title of the question, so if you have any better suggestions, please let me know in the comments.

Take the following simplified TypeScript class:

class Model {
  save():Model {
    // save the current instance and return it
  }
}

The class Modelhas a method save()that returns an instance of itself: a Model.

We can expand Modelas follows:

class SomeModel extends Model {
  // inherits the save() method
}

So it SomeModelinherits save(), but it still returns Model, not SomeModel.

Is there a way, possibly using generics, to set the return type save()to SomeModelon SomeModel, without overriding it inside the inheritance class?

+2
2

. TypeScript 1.7. TypeScript 1.7, , :

class Model {
    save() {
        return this;
    }
}

class SomeModel extends Model {
    otherMethod() {
    }
}

let someModel = new SomeModel().save();
// no compile error since someModel is typed as SomeModel in TS 1.7+
someModel.otherMethod();
+1

, ,
@2019 , return this:

class Model {
  save<T extends Model>(this: T): T {
    // save the current instance and return it
  }
}

, , Model Model, .

Typescript @3 :

class Model {
  save(): this {
    // save the current instance and return it
  }
}
+1

Source: https://habr.com/ru/post/1618657/


All Articles