为什么TypeScript中的“ instance.constructor.staticProperty”不起作用?

时间:2019-05-09 02:33:57

标签: javascript typescript

以下内容无效:

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'.

playground link

为什么不起作用?为什么不足够聪明地知道那里的类型?如何在不直接引用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)

playground link

我已经解决了这种黑客的问题:

function readStaticFoo(obj: Foo) {
  const foo = (obj.constructor as typeof Foo).foo
  console.log(foo)
}

playground link