Closed
Description
Search Terms
"modify readonly for internal classes" - leads to "as any" hack (Goal is to create convinience)
"protected" search - can only be read by derived classes
Suggestion
I find myself looking to complex solutions or longer code to protect state. I'm hoping typescript can be used to reduce code and protect state away from runtime through a public readonly modifier that has write access for internal methods of a class.
Use Cases
I'm hoping to save runtime through typing state protection and avoid extra code such as getters and frameworks that use runtime to manage state.
Examples
class Dog {
readonlyPublic asleep = true
wake() {
// console.trace();
this.asleep = false; // will not throw an error as expected with "readonly"
}
}
const dogA = new Dog();
dogA.asleep = false // Error this is readonlyPublic (forcing us to use the dogA.wake() method to update state)
const isDogAsleep = dogA.asleep // but we can read it publicly without an error..
console.log(isDogAsleep) // => true
-------- update state
dogA.wake();
console.log(dogA.asleep) // => false;
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, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.