2

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'.

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.