【发布时间】:2021-02-19 17:06:56
【问题描述】:
我在尝试让基类推断父类的类型时遇到问题
abstract class Record {
//...
static findRecord(id: number){
// this creates will create an instance of the prototype "this"
// prototype of "this" will equal Node later
return new (Object.getPrototypeOf(this))(id)
}
}
class Node extends Record {
statements(): Array<Statement> {
// ...
}
}
let node = Node.findRecord(1)
// type is "any" (as findRecord doesn't infer the type as "Node", because Object.getPrototypeOf(this)) can equal anything)
node.statements() // This has no typings in vscode
我希望 typescript 知道 Record 的类型将是实例化它的类(在本例中为 Node)
我需要实例化node 的类型为Node,以便.statements() 的类型可用,并且我想避免重复代码并且必须将其放入从@987654326 扩展的每个类中@。
【问题讨论】:
-
显然这是打字稿中很常见的问题https://github.com/Microsoft/TypeScript/issues/5863
标签: typescript