Readonly everything by default
See original GitHub issueSuggestion
🔍 Search Terms
- Readonly by default
- Record readonly by default
- Array readonly by default #32467
- Tuple readonly by default #40316
- Immutable-By-Default Flags #32758
✅ 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
Right now default is that all record/array/tuple properties are mutable, and if you want any of them to be readonly/immutable you should add readonly
flag or use Readonly<...>
. My suggestion is add a flag (or something like that) which will “flip” this - it will turn on “assume everything is read only” in TS project(or module) and add a keyword mutable
when you want to mark something as mutable.
📃 Motivating Example
When using are not mutating data that much and most of the types are assumed to be immutable while very little is mutable you might accidentally mutate something or when trying to understand portion of code, which mostly uses immutable values but some are mutable, you have one option to use readonly/Readonly..
but that code becomes quite noisy. With this flag you can turn on “readonlyByDefault” flag and everthing will be assumed to be readonly and you could mark mutable fields/values with mutable keyword. This way you would know exactly what’s mutable easily and not mutate stuff accidentally.
💻 Use Cases
Probably 99% of react-redux projects do not mutate objects/state or use libraries for immutable structures. Also some teams where folks are using immutable values (and other functional programing practices) would benefit a lot.
I proposed this initially here and then I noticed it had 25 👍 and suggestion to open separate proposal , which I did here.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:198
- Comments:22 (9 by maintainers)
https://github.com/tc39/proposal-record-tuple
I think this would really useful feature since we’d prefer our code to be “immutable”/readonly by default and write exceptions for mutability. Currently it’s very verbose. I had basically exact same proposal in my head for this issue since it can be adopted gradually both – by each codebase and community. Utility type
MutableArray
andMutableInterface
(or whatever) could be introduced in libraries that uses the new modifier on versions that support it and falls back to current behaviour on older versions.