Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Isn't the idea to get a compile time error, rather than a runtime exception?


const exploring = Object.freeze({ immutable: true }) exploring.thing = 'new'

Property 'thing' does not exist on type 'Readonly<{ immutable: true; }>'.ts(2339)

So it would be a simple way to achieve it.


That's opting into immutability, the point of the experiment is having it by default. Plus, that's just the type system preventing you from adding a property. It won't stop you from trying to change the `immutable` field.

I'm genuinely curious, was this AI generated, or just a lack of understanding?


No, you're the one that's incorrect, typescript blocks mutations when you use Object.freeze too: "Cannot assign to 'immutable' because it is a read-only property. (2540)"

You can also use "as const" to get the same behavior without any runtime calls:

    const exploring = { immutable: true } as const
    exploring.immutable = false
              ^ Cannot assign to 'immutable' because it is a read-only property.(2540)
But yes, OP wasn't referring to the article, they were just pointing out the narrower fact that Typescript does in fact have compile-time errors for mutating Object.freeze's return values.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: