本文介绍了TypeScript:在继承类中为静态方法自引用返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript 1.7中使用 ,因为我发现,我们可以在一个返回类中定义一个方法类型的 this ,并且自动地,扩展该类并继承这些方法的任何类将其返回类型设置为它们各自的 this 类型。像这样:

With Polymorphic this in TypeScript 1.7, as I discovered here, we can define a method in a class with a return type of this, and automatically, any classes that extend that class and inherit the methods, will have their return types set to their respective this type. Like so:

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

class SomeModel extends Model {
  // inherits the save() method - return type: SomeModel
}

然而,我要做的是继承 static 方法引用类本身的返回类型。最好在代码中描述:

However, what I'm after is to have an inherited static method with a return type referencing the class itself. It's best described in code:

class Model {
  static getAll():Model[] {
    // return all recorded instances of Model as an array
  }

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

class SomeModel extends Model {
  // inherits the save() method - return type: SomeModel
  // also inherits getAll() - return type: Model (how can we make that SomeModel?)
}

也许我得考虑一下一个不同的方式来实现它,因为TypeScript 1.7中的Polymorphic this 不支持 static 方法 / em>。

Perhaps I'll have to think of a different way to implement this, since Polymorphic this in TypeScript 1.7 does not support static methods by design.

编辑:我猜我们会看到这个Github问题是如何包含的:和

For more information, see https://www.typescriptlang.org/docs/handbook/generics.html#using-class-types-in-generics and https://stackoverflow.com/a/45262288/1268016

这篇关于TypeScript:在继承类中为静态方法自引用返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:07
查看更多