Skip to content
webtype.orgwebtype.org

    ↑↓ move · ⏎ open · esc close

    TS2540

    Read-only property

    Cannot assign to 'x' because it is a read-only property.

    The compiler’s own words. Not translated — this is the string you pasted into a search box.

    The property is marked readonly, which is a compile-time promise not to reassign it — and nothing more than that.

    Reproduction

    const point: { readonly x: number } = { x: 1 }
    
    point.x = 2

    The build asserts this emits exactly this code.

    Why the compiler says this

    readonly is erased at run time. It stops assignments the compiler can see, and it stops nothing else — the same object handed to JavaScript, or reached through a non-readonly alias of the same type, is fully mutable. It documents intent and catches the honest mistakes, which is worth a great deal and is not the same as being frozen.

    Fixes

    1. 01
      const point: { x: number } = { x: 1 }
      
      point.x = 2

      Drop the modifier if the value really is meant to change. readonly on something you mutate is a comment that lies.

    2. 02
      const point: { readonly x: number } = { x: 1 }
      
      const moved: { readonly x: number } = { ...point, x: 2 }

      Or build a new one. This is what readonly is asking you to do, and it is why the modifier is worth keeping: the old value stays valid for anyone still holding it.

    Takeaway

    readonly is a note to other programmers that the compiler happens to enforce. It is not Object.freeze, and it never reaches run time.

    Where to go next

    Errors