Skip to content

Accessing private method with this argument specifier #17694

@unional

Description

@unional

tsc 2.4.1

const keyHandlers = {
  'ArrowDown': function (this: SomeComponent, $event) {
    // error on accessing private method.
    // `this` does not have method private `handleArrowDown`
    this.handleArrowDown($event);
  }
}

export class SomeComponent {
  onKeyDown($event) {
    if (typeof keyHandlers[$event.code] === 'function') {
      keyHandlers[$event.code].call(this, $event);
    }
  }
  private handleArrowDown(_event) {
    // ...
  }
}

Since the ArrowDown function takes the scope of this as SomeComponent, it is part of the class and should be able to access the private methods.

Origin: #9448 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions