Skip to content

Readonly everything by default #42357

Open

Description

Suggestion

🔍 Search Terms

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

Activity

  1. MartinJohns commented on Jan 15, 2021

    @MartinJohns
    Contributor

    Please don't confuse readonly and immutable. TypeScript does not provide any mechanism to represent immutable data structures. For this reason I wouldn't add a keyword "mutable", because that kinda implies the opposite is immutable.

  2. safareli commented on Jan 15, 2021

    @safareli
    Author

    👍 Yeah, for example writable could be the name of the keyword. I don't have strong opinion on names whatever would be acceptable by maintainers/community is good for me.

  3. MartinJohns commented on Jan 15, 2021

    @MartinJohns
    Contributor

    00ff0000red From the proposal:

    and add a keyword mutable when you want to mark something as mutable.

    Instead of mutable being the default with the option to opt to readonly, the suggestion is to do it the other way around.

    // Currently
    const x1: [number, number] = [3, 9]; // Mutable
    const x2: readonly [number, number] = [3, 9]; // Readonly
    
    // Suggested
    const x3: [number, number] = [3, 9]; // Readonly
    const x4: mutable [number, number] = [3, 9]; // Mutable
    
  4. artursvonda commented on Jan 18, 2021

    @artursvonda

    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 and MutableInterface (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.

  5. boris-kolar commented on Jan 19, 2021

    @boris-kolar

    I love the idea, because I find myself writing readonly all the time. Immutable by default would also be very useful for compilers that compile TypeScript to wasm/native code (e.g. AssemblyScript, TypeScript Static). Also, allowing readonly for classes, interfaces and object types would be nice.

    readonly interface Foo {
        foo: number // equivalent to: readonly foo: number
    }
    
    readonly class FooClass {
        static foo: number = 42 // equivalent to: static readonly foo: number = 42
        foo: number = 0 // equivalent to: readonly foo: number = 0
    }
    
    type Bar = readonly {
        bar: string // equivalent to: readonly bar: string
        baz: { z: number } // equivalent to: readonly baz: { readonly z: number }
    }

    In addition, I think methods should be readonly by default:

    interface Foo {
        foo(): void
    }
    let foo: Foo = { foo: () => { } }
    foo.foo = () => { throw 0 } // foo should be readonly by default
  6. lautarodragan commented on Jan 21, 2021

    @lautarodragan

    Is this a dup of #32758?

  7. isaac-weisberg commented on Apr 26, 2021

    @isaac-weisberg

    Yeah, it makes no sense that I have to write readonly for every single interface member considering that this is my primary tool for encapsulation and access control

    I can create a readonly member on a class that implements an interface with a member of the same name and type that would satisfy the interface requirement, but suddenly, it doesn't translate - readonly on the class, but if you hold onto the object by its interface, it's suddenly mutable...

  8. benwiley4000 commented on Jul 29, 2021

    @benwiley4000

    Oh, okay, I see. In that case, it wouldn't be nearly as bad, except maybe that all of the lib typings would need to be updated, e.g. all TypedArrays are inherently mutable.

    I'm sure whatever implementation this takes will need to basically apply this rule only to the project and not to external modules. Any 3rd party module typings would still be "writable by default" (unless the typings file somehow declares readonly-by-default, which could/should be an option).

    I can see it potentially becoming annoying to have to declare any piece of non-primitive data passed to a third party library "writable," but I imagine this annoyance would lesson over time as more libraries adopt the readonly-by-default declaration.

    In the meantime there could be two workarounds to avoid excessive writable definitions: A) defensive copying (to writable) before passing (when you really don't trust the library too much), and B) as writable casting while passing, which would be unsafe but acceptable in cases where you know the library doesn't mutate the data.

  9. MaxGraey commented on Jul 30, 2021

    @MaxGraey

    currently:

    const tup1 = [1, 2]                             // [number, number]
    const tup2: readonly [number, number] = [1, 2]  // readonly [number, number]
    const tup3 = [1, 2] as const                    // readonly [number, number]

    new:

    const tup1 = [1, 2]                    // readonly [number, number]
    const tup2: [number, number] = [1, 2]  // [number, number]
    const tup3 = [1, 2] as mut             // [number, number]
    const tup4 = tup3 as const             // readonly [number, number]
  10. 3 remaining items

  11. TheUnlocked commented on Nov 13, 2022

    @TheUnlocked

    Rather than have readonly by default (which seems dangerous for interacting with libraries), I think it would make more sense for the flag to just disallow unannotated array/object types (and maybe a separate flag for whether literals should be writable/readonly, though that might not be worth it).

  12. anilanar commented on Nov 29, 2022

    @anilanar
    Contributor

    Luke Miles (@qpwo)

    Let me give an example:

    // node_modules/sort-library/index.d.ts
    /**
     * Sorts an array in place
     */
    export function sort(arr: number[]): void;

    Today

    // src/index.ts
    
    import { sort } from 'sort-library';
    
    const mutableArray: number[] = [1, 2, 3];
    const immutableArray: readonly number[] =  [1, 2, 3];
    
    // no error
    sort(mutableArray);
    
    // The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
    sort(immutableArray);

    Everything readonly by default

    // src/index.ts
    
    import { sort } from 'sort-library';
    
    const mutableArray: mutable number[] = [1, 2, 3];
    const immutableArray: number[] =  [1, 2, 3];
    
    // no error
    sort(mutableArray);
    
    // no error... WHAT???
    sort(immutableArray);

    The reason the last sort doesn't emit a type error is because a defaultReadonly: true option in tsconfig.json would apply to everything, including library code in node_modules. So all types in all declaration files in node_modules would become readonly by default. So export function sort(arr: number[]): void; becomes export function sort(arr: readonly number[]): void; which is a lie because that function mutates the array in its javascript implementation file.

  13. MartinJohns commented on Nov 29, 2022

    @MartinJohns
    Contributor

    Anıl Anar (@anilanar) Please don't confuse read-only with immutable.

  14. anilanar commented on Nov 29, 2022

    @anilanar
    Contributor

    Martin Johns (@MartinJohns) Perhaps this issue and its dual #32758 require some enlightenment about that. Does true immutability exist in TS? If it doesn't, don't we refer to readonly fields and ReadonlyArrays when we say immutable in this context?

  15. anilanar commented on Nov 29, 2022

    @anilanar
    Contributor

    Even the type error itself mentions mutability: The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.

  16. MartinJohns commented on Nov 29, 2022

    @MartinJohns
    Contributor

    Anıl Anar (@anilanar) Immutability can't be represented in TypeScripts type system as of today. Read-only only means it's read only via that interface. A good example is that mutable objects can be implicitly assigned to the read-only versions. The object is read only, but it's not immutable, it can still be mutated just fine. (side note: the read-only version can be passed implicitly to the mutable version as well.)

  17. parischap commented on Jun 30, 2023

    @parischap

    Hi! Has any progress been made on that topic? I am also very interested in a readonly bu default typescript flag in tsconfig.json that would apply only to the files covered by this tsconfig.json.

  18. Tungetyt commented on Aug 22, 2023

    @Tungetyt

    Please let it happen.

  19. rhaksw commented on Nov 6, 2024

    @rhaksw

    Martin Johns (@MartinJohns) Anıl Anar (@anilanar) to move this forward, is correct that Irakli Safareli (@safareli) would need to modify the proposal to account for the impact on library code, as Anıl Anar (@anilanar) mentioned here in Jan 2021, and here in Nov 2021?

    CC Alexander Kachkaev (@kachkaev) for input on why the current proposal is undesirable.

  20. anilanar commented on Nov 6, 2024

    @anilanar
    Contributor

    Robert Hawkins (@rhaksw) This is up to the TS core team to come up with a proposal as only they have the ultimate long-term vision, considering this feature would require a radical approach by either introducing a new tsconfig field, or a file-scoped pragma or similar.

    Right now "readonly" doesn't have too much of an adoption neither in libraries nor in application code because:

    1. Library authors avoid readonly. They assume users don't use readonly even for readonly arrays/records. They think, if they start using readonly, the library will become more difficult to use.
    2. The same logic applies to application coders. They don't use readonly because using it makes libraries harder to use.

    So this is a vicious cycle that is difficult to get out of. However there's still hope if we make readonly less verbose, e.g. by making it the default as opt-in.

  21. rhaksw commented on Nov 6, 2024

    @rhaksw

    Thank you for that explanation, Anıl Anar (@anilanar). Speaking as an application developer, I do not use "readonly" (either the flag, Readonly<...>, or const ... as const, not because it makes libraries harder to use, but rather because it requires me to alter all of my variable declarations. If a library required me to mutate its objects in my own code, then I simply would not use it.

    This proposal interested me because it would not require me to alter all variable declarations. I understand that if I adopted the proposed "readonlyByDefault", then that may limit the libraries available to me. But then, unless I am misunderstanding something here, I would also consider those to be poorly written libraries that I shouldn't be using anyway.

  22. rhaksw commented on Nov 23, 2024

    @rhaksw

    Thinking about this again, maybe an ESLint plugin such as eslint-plugin-functional would be more practical than trying to change TypeScript.

  23. ardokirsipuu commented on Dec 19, 2024

    @ardokirsipuu

    Thinking about this again, maybe an ESLint plugin such as eslint-plugin-functional would be more practical than trying to change TypeScript.

    Although targeting the same problem, it seems to be a very different solution. One gets rid of the need for having boilerplate while the other enforces me to write this boilerplate. 🙈

    EDIT: Or perhaps instead of the rules enforcing to make everything read-only you were thinking of the rules not allowing mutation? There are a lot of different rules in that ESLint pugin.

  24. rhaksw commented on Dec 19, 2024

    @rhaksw

    Yes, I meant the rule in your second link, functional/immutable-data. Thanks!

  25. andyearnshaw commented on Feb 26, 2026

    @andyearnshaw

    Originally I posted this comment in #7770, as I found that issue before this one. However, I think it's valid as an example here too.


    I frequently run into the same scenario over and over in React where I see people reaching for memoization unnecessarily. It usually ends up looking like this:

    function MyComponent({ config }: Props) {
      // Prevent recreating the default array on every call to MyComponent
      const someArray = useMemo(() => config?.someArray ?? [], [config]);
    
      return <SomeOtherComponent someArray={someArray};
    }

    This is a bit of a trigger for me when I'm reviewing pull requests, but I see it several times per week. I'll usually ask the author to change it to use an empty array outside the scope of the component:

    // Frozen because any function/component that modifies it would be disastrous.
    const DEFAULT_ARRAY = Object.freeze([]);
    
    function MyComponent({ config }: Props) {
      // Prevent recreating the default array on every call to MyComponent
      const someArray = config?.someArray ?? DEFAULT_ARRAY as Props['someArray'];
    
      return <SomeOtherComponent someArray={someArray} />;
    }

    However, this might produce a potential refactoring hazard, because SomeOtherComponent is not expecting a readonly array. Usually, I end up rewriting it to be as unknown as Props['someArray'], one of the few instances of as unknown as I will tolerate in production code.

    What I would really like to see is TypeScript move towards read-only types by default, with a writable state to counter the readonly state.

    // The Foo type has the readonly modifier.
    type Foo = {
      someProp: number
    };
    
    // Incorrect
    function mySideEffectFunction(
      foo: Foo,
    ) {
      foo.someProp = 2; // type error, cannot modify readonly object
    
      // ...
    }
    
    // Correct
    function mySideEffectFunction(
      foo: Writable<Foo>,
    ) {
      foo.someProp = 2;
    
      // ...
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions