TypeScript中的后期静态绑定和实例方法

时间:2016-07-01 06:24:28

标签: python typescript static polymorphism instance

非常好奇TypeScript中如何/为什么需要以下技巧。正在使用基本的classstatic构造,然后继承,最后引用static方法中的instance属性。我可能不会以这种方式实现任何东西......但我确实很困惑为什么以下工作:

class Foo {
  msg: string;
  static name: string = 'Foo';
  static sayHi(): string {
    return `hello from ${this.name}`;
  }
  constructor() {
    // this.msg = `I am ${Foo.name}`;
    //   2x `I am Foo`

    // this.msg = `I am ${this.name}`;
    //   error TS2339: Property 'name' does not exist on type 'Foo'.

    // this.msg = `I am ${this.constructor.name}`;
    //   error TS2339: Property 'name' does not exist on type 'Function'.

    const cls = <typeof Foo>this.constructor;
    this.msg = `I am ${cls.name}`;
  }
}

class Bar extends Foo {
  static name: string = 'Bar';
}

console.log(Foo.sayHi());   // hello from Foo
console.log(Bar.sayHi());   // hello from Bar

console.log((new Foo()).msg);   // I am Foo
console.log((new Bar()).msg);   // I am Bar

(我tsc 1.8.10this answer中的更新让它正常运行

如果你跳到@ basarat的回复,为什么类型断言神奇地使一切都有效?

与类似的python相比:

class Foo(object):
  name = 'Foo'
  @classmethod
  def sayHi(cls):
    return 'hello from {}'.format(cls.name)
  def __init__(self):
    self.msg = 'I am {}'.format(self.name);

class Bar(Foo):
  name = 'Bar'

print(Foo.sayHi())  # hello from Foo
print(Bar.sayHi())  # hello from Bar

print(Foo().msg)  # I am Foo
print(Bar().msg)  # I am Bar

0 个答案:

没有答案
相关问题