41 ms·
> If you figure out how to do this completely, please contact me—I must know! I think you want to use a TypeScript compiler extension / ts-patch This is a bit
by zero_shift 10mo ago
> If you figure out how to do this completely, please contact me—I must know!
I think you want to use a TypeScript compiler extension / ts-patch
This is a bit difficult as it's not very well documented, but take a look at the examples in https://github.com/nonara/ts-patch https://github.com/nonara/ts-patch
Essentially, you add a preprocessing stage to the compiler that can either enforce rules or alter the code
It could quietly transform all object like types into having read-only semantics. This would then make any mutation error out, with a message like you were attempting to violate field properties.
You would need to decide what to do about Proxies though. Maybe you just tolerate that as an escape hatch (like eval or calling plain JS)
Could be a fun project!
- Cthulhu_ 10mo agoOne "solution" is to use Object.freeze(), although I think this just makes any mutations fail silently, whereas the objective with this is to make it explicit and a type error.
- dunham 10mo agoI thought Object.freeze threw an exception on mutation. Digging a little more, it looks like we're both right. Per MDN, it throws if it is in "use strict" mode and silently ignores the mutation otherwise.
- zelphirkalt 10mo agoIsn't the idea to get a compile time error, rather than a runtime exception?
- rezistik 10mo agoconst 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.
- ItsHarper 10mo agoThat'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?
- nightpool 10mo agoNo, 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.
- giancarlostoro 10mo agoI used to have code somewhere that would recursively call Object.freeze on a given object and all its children, till it couldn't "freeze" anymore.