rocketer
rocketer

Reputation: 1071

Error when using instance property from static method in TypeScript

I have this TypeScript class:

export class UserCredentials {
  public name: string;

  static getName() {
    return this.name;
  }
}

When I remove the static everything works fine. But with it, I have the following compiler error : Property 'name' does not exist on type 'typeof UserCredentials'.

Upvotes: 2

Views: 1236

Answers (2)

Azamat  Mirvosiqov
Azamat Mirvosiqov

Reputation: 715

In this kind of situations you must only (if you don't want make property 'name' static) create new instance inside static method

export class UserCredentials {
    public name: string;

    static getName() {
        const userCredentials = new UserCredentials(); // <--- create this
        return userCredentials.name;
    }
}

Upvotes: 1

Amid
Amid

Reputation: 22332

In static method you cant access "this" instance or its properties. Mark your field with "static" modifier to make it work:

public static name: string;

Upvotes: 3

Related Questions