Skip to content

Allow readonly / const keyword for class member function definitionsΒ #47003

Closed
@thw0rted

Description

@thw0rted

Suggestion

πŸ” Search Terms

readonly class member function assign overwrite

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Class definitions should provide a way to protect member function definitions from accidentally being overwritten.

The syntax public readonly callback() { ... } is currently an error, as is public const callback() { ...}. I can see where some people might get confused or surprised about the use of one of these keywords, thinking it applies to the return value, so I'm open to other suggestions -- but frankly, the current behavior is surprising.

πŸ“ƒ Motivating Example

This is currently valid code:

class Foo {
  callback() { ... }
  start() {
    let callback = x => { this.doX(x); };
    if (someCondition) {
      // Oops, I meant to type "callback = ..."
      this.callback = y => { this.doY(y); };
      // I just overwrote the implementation of `Foo#callback`
    }
    library.doThing(callback);
  }
}

As far as I can tell, the only way to catch the above logic error is to declare all methods of Foo as const member variables, e.g.

class Foo {
  public readonly callback;
  constructor() {
    this.callback = (function() { ... }).bind(this);
  }
}

πŸ’» Use Cases

This probably doesn't actually come up that often in the wild, but it can produce difficult-to-trace logic errors at runtime when it does. The workaround posted in the previous section is unwieldy, and some syntactic sugar would make the feature more likely to be used.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions