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