以下内容无效:
abstract class Foo {
static get foo() { return 123 }
}
class Bar extends Foo {
static get foo() { return 456 }
}
let b = new Bar
console.log(b.constructor.foo) // ERROR: Property 'foo' does not exist on type 'Function'.
为什么不起作用?为什么不足够聪明地知道那里的类型?如何在不直接引用Bar
类的情况下实现?
我想使用b.constructor
的形式,因为我可能不知道实例将使用哪个子类:
// ...continuing from before...
class Baz extends Foo {
static get foo() { return 42 }
}
class Lorem extends Foo {
static get foo() { return 3.14 }
}
function readStaticFoo(obj: Foo) {
console.log(obj.constructor.foo) // ERROR: Property 'foo' does not exist on type 'Function'.
}
const baz = new Baz
const lor = new Lorem
readStaticFoo(baz)
readStaticFoo(lor)
我已经解决了这种黑客的问题:
function readStaticFoo(obj: Foo) {
const foo = (obj.constructor as typeof Foo).foo
console.log(foo)
}
答案 0 :(得分:0)