Property or Indexer Cannot Be Assigned to It Is Read Only

In TypeScript two.0, the readonly modifier was added to the language. Properties marked with readonly can only be assigned to during initialization or from within a constructor of the same course. All other assignments are disallowed.

Let's accept a look at an instance. Here'southward a uncomplicated Point type that declares two read-simply properties, x and y:

                                    type                                          Point                                          =                              {                                                                  readonly                              x              :                                          number              ;                                                                  readonly                              y              :                                          number              ;                                      };                              

We tin can now create an object representing the signal (0|0), the origin, and initialize both 10 and y with the value 0:

                                    const                                          origin              :                                          Point                                          =                              {                            x              :                                          0              ,                            y              :                                          0                              };                              

Yet, considering x and y are marked readonly, nosotros cannot change the value of either property afterwards:

                                    // Error: Left-hand side of consignment expression                                      // cannot be a constant or read-but property                                      origin.              10                                          =                                          100              ;                              

#A More Realistic Example

While the to a higher place example might seem contrived (and it is), consider a function like the following:

                                    function                                          moveX              (p              :                                          Bespeak              , kickoff              :                                          number              )              :                                          Point                              {                                                      p.              ten                                          +=                              beginning;                                                                  return                              p;                                      }                              

The moveX function should not modify the 10 holding of the betoken it was given. Considering of the readonly modifier, the TypeScript compiler will yell at you if yous attempt:

Forbidden assignment to readonly property in TypeScript

Instead, moveX should render a new indicate with updated holding values, which could wait similar this:

                                    role                                          moveX              (p              :                                          Point              , first              :                                          number              )              :                                          Point                              {                                                                  render                              {                                                                  x              :                              p.              10                                          +                              offset,                                                                  y              :                              p.              y                                                      };                                      }                              

Now the compiler is happy because we're no longer trying to assign a value to a read-only property. We're creating a new point whose backdrop are initialized with updated values, which is perfectly fine.

#Read-Just Form Properties

You tin can also apply the readonly modifier to properties alleged within a class. Here'southward a Circle class with a read-only radius property and a gettable area holding, which is implicitly read-but considering there's no setter:

                                    class                                          Circle                              {                                                                  readonly                              radius              :                                          number              ;                                                                                          constructor              (radius              :                                          number              ) {                                                                  this              .              radius                                          =                              radius;                                                      }                                                                                          go                                          expanse              () {                                                                  return                                          Math              .              PI                                          *                                          this              .              radius                                          **                                          2              ;                                                      }                                      }                              

Notation that the radius is squared using the ES2016 exponentiation operator. Both the radius and the area property tin can be read from exterior the class (because neither one is marked private), but not written to (because both are marked readonly):

                                    const                                          unitCircle                                          =                                          new                                          Circle              (              one              );                                      unitCircle.              radius              ;                            // 1                                      unitCircle.              area              ;                            // 3.141592653589793                                                              // Error: Left-hand side of assignment expression                                      // cannot exist a abiding or read-simply property                                      unitCircle.              radius                                          =                                          42              ;                                                              // Error: Left-hand side of consignment expression                                      // cannot be a constant or read-only property                                      unitCircle.              area                                          =                                          42              ;                              

#Read-Just Index Signatures

Additionally, index signatures tin exist marked with the readonly modifier. The ReadonlyArray<T> type makes use of such an index signature to preclude assignments to indexed backdrop:

                                    interface                                          ReadonlyArray              <              T              > {                                                                  readonly                              length              :                                          number              ;                                                                  // ...                                                                  readonly                              [due north              :                                          number              ]              :                                          T              ;                                      }                              

Because of the read-but index signature, the compiler flags the following consignment every bit invalid:

                                    const                                          primesBelow10              :                                          ReadonlyArray              <number>                            =                              [              2              ,                            3              ,                            5              ,                            7              ];                                                              // Fault: Left-hand side of assignment expression                                      // cannot be a constant or read-only property                                      primesBelow10[              four              ]                            =                                          11              ;                              

#readonly vs. Immutability

The readonly modifier is part of TypeScript's type organization. It's only used by the compiler to check for illegal holding assignments. Once the TypeScript code has been compiled to JavaScript, all notions of readonly are gone. Experience gratuitous to play around with this trivial sample to run into how read-just backdrop are transpiled.

Because readonly is but a compile-time artifact, there's no protection against property assignments at runtime whatsoever. That said, it'due south another feature of the type organization that helps you write correct code by having the compiler check for unintended belongings assignments from inside your TypeScript code base.

palaciosfrand1961.blogspot.com

Source: https://mariusschulz.com/blog/read-only-properties-in-typescript

0 Response to "Property or Indexer Cannot Be Assigned to It Is Read Only"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel