【问题标题】:I have a question for Typescript static function我对 Typescript 静态函数有疑问
【发布时间】:2019-05-11 17:25:43
【问题描述】:

这是我的代码。

class BaseClass {
   // some static method
   static someMethod() {
   }
}
class ChildClass extends BaseClass{

}
class AnotherClass {
   protected variable: BaseClass; // It works while the type is any

   protected someFunction() {
      return this.variable.someMethod(); // Editor shows that there's no someMethod in BaseClass
   }
}

问题是,我希望 AnotherClass 中的受保护变量存储类函数,而不是类实例。

有可能吗?

谢谢。

对不起,我的英语不好。

【问题讨论】:

标签: typescript


【解决方案1】:

在您的示例中,variable 属性是BaseClass 的一个实例,而不是类本身。

variable的类型需要是BaseClass的类型,即typeof BaseClass

class AnotherClass {
  protected variable: typeof BaseClass;

  public constructor(v: typeof BaseClass) {
    this.variable = v;
  }

  protected someFunction() {
    return this.variable.someMethod();
  }
}


const a: AnotherClass = new AnotherClass(BaseClass);

【讨论】:

    【解决方案2】:

    这个错误是由 tsc 而不是编辑器引起的。

    指出你代码中的一些问题。

    class AnotherClass {
        protected variable: BaseClass; // This is mean variable is instance of BaseClass
        protected someFunction() {
            return this.variable.someMethod(); // So you cannot access a static method of an instance
        }
    }
    

    如果你想访问一个类的静态方法。您应该从类对象调用,而不是类的实例。所以你应该将变量成员的类型从BaseClass修改为typeof BaseClass
    下面是一个简单的示例。为了简单的概念,我修改了成员的封装。

    class BaseClass {
      static someMethod(): void {}
    }
    
    class DeriveClass extends BaseClass {
    }
    
    class AnotherClass {
        public variable: typeof BaseClass = BaseClass;
        public someFunction() {
            return this.variable.someMethod();
        }
    }
    
    let instance = new AnotherClass();
    instance.variable = DeriveClass; // This is accepted, because DeriveClass extended from BaseClass
    instance.someFunction();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 2017-02-22
      • 2019-05-06
      • 1970-01-01
      相关资源
      最近更新 更多