构建以下 typescript 代码时出现以下错误。
Property 'runStaticMethod' is a static member of type 'DemoClass'
typescript 代码:
export class Main {
constructor(private demo: DemoClass) { }
public run() {
this.demo.runStaticMethod();
}
}
export class DemoClass {
public static runStaticMethod() {
console.log('run...');
}
}
new Main(DemoClass).run();
我收到以下信息
console
构建上述内容时出错 typescript
代码。但是javascript
代码按预期运行。控制台错误:
Chitty:tsc NatarajanG$ tsc
src/index.ts:5:19 - error TS2576: Property 'runStaticMethod' is a static member of type 'DemoClass'
5 this.demo.runStaticMethod();
~~~~~~~~~~~~~~~
Chitty:tsc NatarajanG$
最佳答案
因为它是一个静态属性,您应该按照 TS 要求的方式访问它:DemoClass.runStaticMethod()
, 尽管 javascript 支持 this.demo.runStaticMethod()
.
https://www.typescriptlang.org/docs/handbook/classes.html#static-properties
Each instance accesses this value through prepending the name of the class. Similarly to prepending
this
. in front of instance accesses, here we prependGrid
. in front of static accesses.
关于typescript - 属性 'runStaticMethod' 是 'DemoClass' 类型的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55262583/