Is Object.freeze
suggested in Typescript or is there other way of making sure object remains immutable?
Since const
only guards instance, but not properties, this is obviously not an answer I’m looking for.
Advertisement
Answer
is there other way of making sure object remains immutable?
It depends on the level of insurance that you want to have.
If you want to make sure that no consumer, be it TypeScript or JavaScript code, could modify object properties at runtime, Object.freeze
is the way to do it.
If compile-time checks are sufficient, for example when all consumer code is guaranteed to be TypeScript-only and typechecked, you can use ReadOnly
generic type, which takes an object type and makes all properties readonly
. In fact, Object.freeze()
is declared in library type definitions as returning ReadOnly
-modified type of its argument:
freeze<T>(o: T): Readonly<T>;
For seal
, there is no way to represent sealed object in the type system, Object.seal()
is declared to return the same type it receives:
seal<T>(o: T): T;
and Object.seal()
is the only way to go.