Orelsanpls
Orelsanpls

Reputation: 23505

typescript typing with static member of class

I want to access the static member of a class through an object of this class.

I do it using obj.constructor. It works well except with the typescript linter which says

Property 'getName' does not exist on type 'Function'

class Foo {
    public static getName(): string {
        return 'foo';
    }
}

const foo = new Foo();

const name: string = foo.constructor.getName();

I tried using : const name: string = (foo.constructor as Foo).getName();

but it gives me

Property 'getName' is a static member of type 'Foo'


EDIT :

It worked using : const name: string = (foo.constructor as typeof Foo).getName();

Is there any way it could work without manually casting the class?



INFO : I cannot call it directly using Foo.getName() in my specific case

Upvotes: 3

Views: 8911

Answers (2)

Jared Smith
Jared Smith

Reputation: 21926

You have to fudge it with the compiler if you don't have access to the class. Note that this is a filthy dirty hack, but sometimes you just have to tell the compiler "shut up, I know what I'm doing".

class Foo {
  public static getName() {
    return 'foo';
  }
}

const foo = new Foo();

interface FudgeIt {
  getName: () => string,
}

// compiler won't let us cast a function to
// a random interface without declaring it
// unknown first.
const c: unknown = foo.constructor;
(c as FudgeIt).getName();

Here's a link to the relevant playground

Upvotes: 1

Karol Majewski
Karol Majewski

Reputation: 25790

Static methods are accessed by calling the constructor directly:

Foo.getName()

If for some reason you don't have access to the constructor, assert foo.constructor to be of its type.

const name: string = (foo.constructor as typeof Foo).getName();

Upvotes: 4

Related Questions