Typescript Static Method 不支持在 instance 实例里面去调用

最近用typescript,遇到了一个场景需要把每个component的title字段给提取出来,这个字段设置为了static,
在父类的方法里面是需要去调用每个子类的static对应属性的,在其他语言里面可以这样用。

PHP: $this->staticMethod(); or $this::staticMethod();
Python: self.__class__.staticMethod()
Ruby: self.class.staticMethod
Objective-C: [[self class] staticMethod]
Swift: self.dynamicType.staticMethod()

在Javascript里面可以这样来。

class StaticMethodCall {
      static staticProperty = 'static property';

  constructor() {
    console.log(StaticMethodCall.staticProperty); // 'static property'
    console.log(this.constructor.staticProperty); // 'static property'
    console.log(StaticMethodCall.staticMethod()); // 'static method has been called.'
    console.log(this.constructor.staticMethod()); // 'static method has been called.'
  } 

  static staticProperty = 'static property';
  static staticMethod() {
    return 'static method has been called.';
  }
}
(new StaticMethodCall).constructor.staticMethod()

结果为

static property
VM256:6 static property
VM256:7 static method has been called.
VM256:8 static method has been called.
'static method has been called.'

但在ts里面是不行的,
比较好的解决方案是每个类都添加下这行代码。太扯淡了。

class C {
    ['constructor']: typeof C;
}

github上面相关的issue 15年就提出来 https://github.com/microsoft/TypeScript/issues/3841
, 正如这条评论说的一样。 This is one of the reasons why I
stopped to use TS. It’s too useless for OOP programming. You probably
should do this too. Over they years, instead of fixing existing issues
M$$oft introduced a lot of unnecessary and unjustified complex features
that only create unnecessary mess.

ts
添加了太多无用的功能增加语言复杂程度,却连这个很常用的功能都没有添加,ts代码最终会跟着Javascript的特性走,没有特殊的场景需要使用不建议使用ts。等着Javascript像PHP一样增加静态类型吧。个人项目更不要用typescript降低开发效率。

Leave a comment

Your email address will not be published. Required fields are marked *