frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Experiment: Making TypeScript Immutable-by-Default

https://evanhahn.com/typescript-immutability-experiment/
25•ingve•1h ago

Comments

jbreckmckye•47m 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.

This is a bit difficult as it's not very well documented, and, the API might change with the Go rewrite.

But, you can basically invent a middleware to the compilation process.

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!

voidUpdate•27m ago
How do immutable variables work with something like a for loop?
foxygen•25m ago
You use something else like map/filter/reduce or recursion.
tgv•16m ago
Unless you need the index, you can write: for (const x of iterable) { ... } or for (const attribute in keyValueMap) { ... }. However, loops often change state, so it's probably not the way to go if you can't change any variable.
tantalor•4m ago
Is TFA (or anyone else for that matter) actually concerned with "immutable variables"?

e.g., `let i = 0; i++;`

They seem to be only worried about modifying objects, not reassignment of variables.

tyleo•11m ago
This is tangential but one thing that bothers me about C# is that you can declare a `readonly struct` but not a `readonly class`. You can also declare an `in` param to specify a passed-in `struct` can’t be mutated but again there’s nothing for `class`.

It may be beside the point. In my experience, the best developers in corporate environments care about things like this but for the masses it’s mutable code and global state all the way down. Delivering features quickly with poor practices is often easier to reward than late but robust projects.