构建以下打字稿代码时,出现以下错误。
Property 'runStaticMethod' is a static member of type 'DemoClass'
打字稿代码:
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$
答案 0 :(得分:2)
由于它是静态属性,因此尽管JavaScript支持DemoClass.runStaticMethod()
,您仍应按照TS要求的方式访问它:this.demo.runStaticMethod()
。
https://www.typescriptlang.org/docs/handbook/classes.html#static-properties
每个实例都通过在类名前添加访问此值。与前置
this
类似。在实例访问之前,这里我们在Grid
之前。在静态访问之前。
答案 1 :(得分:0)
我的测试表明,为 interface
添加 DemoClass
并为 runStaticMethod
定义可以解决错误,例如...
export interface DemoClass {
runStaticMethod(...args: any[]): any;
}
...为了方便复制/粘贴,这里是进一步自定义的起点...
export interface DemoClass {
runStaticMethod(...args: any[]): any;
}
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();