10

I am getting the following error when I build the following typescript code.

Property 'runStaticMethod' is a static member of type 'DemoClass'

Typescript Code:


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();

I am getting the following console error when I build the above typescript code. But the javascript code is running as expected.

Console Error:

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$ 

Natarajan Ganapathi
  • 551
  • 1
  • 7
  • 19
  • 4
    Your `demo` property is not of type `DemoClass`, it's of type `typeof DemoClass`. Change it to that and it should work (although you might choose to refactor that to something more general... otherwise just have `Main` depend on the `DemoClass` constructor without having to pass it in). See [this answer](https://stackoverflow.com/a/50396312/2887218) if you are confused by the difference between `DemoClass` the type and `DemoClass` the value. – jcalz Mar 20 '19 at 14:05
  • 1
    Also note that, as written, the type `DemoClass` is empty (no non-static properties or methods), which is [muddling up the issue](https://github.com/Microsoft/TypeScript/wiki/FAQ#why-do-these-empty-classes-behave-strangely). Add an instance property to `DemoClass` in your code above and you'll also get the error on `new Man(DemoClass)`, since `DemoClass` *should not be* of type `DemoClass` itself. – jcalz Mar 20 '19 at 14:08

2 Answers2

7

Because it's a static property and you should access it in the way how TS requires it: DemoClass.runStaticMethod(), despite javascript supports 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 prepend Grid. in front of static accesses.

satanTime
  • 12,631
  • 1
  • 25
  • 73
0

My tests show that adding an interface for DemoClass with a definition for runStaticMethod resolves errors, eg...

export interface DemoClass {
    runStaticMethod(...args: any[]): any;
}

... And for easy copy/paste here's a starting point to customize further...

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();

S0AndS0
  • 860
  • 1
  • 7
  • 20