DEV Community

Discussion on: Easy functional programming techniques in TypeScript for everyone

Collapse
 
aminnairi profile image
Amin

Hi there, great article! Did you know that you can use Object.freeze to prevent mutating an array or an object?

const list = Object.freeze([])

list.push(1)
// Throws an error
Collapse
 
deepu105 profile image
Deepu K Sasidharan

Yes, I thought of writing about it but then missed

Collapse
 
macsikora profile image
Pragmatic Maciej

It will couse runtime exception. So Object.freeze is not useful in terms of TS.

Collapse
 
aminnairi profile image
Amin

Hi Maciej. You are absolutely right! That's why it is so good coupled with TypeScript which can prevent mutating a freezed object by refusing to transpile the file.

Thread Thread
 
macsikora profile image
Pragmatic Maciej

Still I see readonly as a tool for the job. Object.freeze is fully run-time thing and it is decoupled from type definition. Declaration of readonly is included into type definition, so it is explicit. I don't think run-time block is needed here.