↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

Immutability in TypeScript

The post says immutability makes code simpler and less error prone, and that TypeScript can enforce it at compile time. It first shows a Person class with readonly fields, then shows that changing a property or adding new ones is blocked.

Reading notes
#

  • Immutability is presented as a top priority because it leads to simpler and less error prone code.
  • JavaScript allows adding attributes to objects even when they were not declared.
  • TypeScript can enforce immutable code at compile time.
  • A Person class with readonly name, surname, and city only allows those values to be assigned in the constructor.
  • If a field must change, the object has to be copied and rebuilt with the new value.
  • Copying becomes painful when an object has many properties, and adding a new attribute breaks the copy code.
  • The builder pattern is introduced as a way to build and copy Person objects more conveniently.
  • The Person constructor is made private so the object can only be created through Person.builder().
  • PersonBuilder can take an existing Person, change selected fields, and build a new Person.
  • A readonly array property is still mutable, so push and pop can still change its contents.
  • To handle that case, the post switches to Immutable.js and uses Set for the cities field.
  • Immutable.js is described as providing data structures such as List, Stack, Map, OrderedMap, Set, OrderedSet, and Record.
  • With an immutable set, add returns a new set instead of changing the original one.
  • The author says this approach is used at Hyperdoc to build immutable objects.