3 ms·
Some people hate enums but they’re the only easy form of nominal typing in typescript, and for that alone you can pry them from my cold dead hands.
by alpinisme 1y ago
Some people hate enums but they’re the only easy form of nominal typing in typescript, and for that alone you can pry them from my cold dead hands.
- eyelidlessness 1y agoI agree completely. But I also know I’m in the extreme minority. Now I just use erasable syntax even on my personal projects because it’s less friction. Maybe someday the enum proposal in TC39 will mix this up a bit!
- matt_kantor 1y agoI find that for most of my use cases, branded types[1] are close enough to nominal (especially if you use a private `unique symbol` as the brand). [1]: https://www.learningtypescript.com/articles/branded-types https://www.learningtypescript.com/articles/branded-types
- alpinisme 1y agoI did say easy and by that I also meant lightweight. You can just use a string not an object with a relatively esoteric symbol in addition to whatever serializable value you need.
- goodoldneon 1y agoWhy is nominal typing desirable?
- jy14898 1y agoexample: type FireNuke = boolean; type DontFireNuke = boolean; function perhapsFireNuke(action: FireNuke); you wouldn't want to call perhapsFireNuke with DontFireNuke, even though the types are compatible
- veidr 1y agounless... you know
- eyelidlessness 1y agoTo be fair, this is a better example of booleans being a poor fit for modeling many problems. And it’s solvable without even addressing either issue (eg how this is modeled in the real world with multiple affirmatives).
- rictic 1y agoPrivate fields, unique symbols, there's many ways to do nominal typing in TypeScript, depending on what you want.
- eyelidlessness 1y agoI think that’s part of the problem: there’s no canonical idiom. The other part of the problem (IME) is that the biggest gap in nominal typing support is exactly what enum solves: nominal primitives. Yes, you can kinda get there with branding, but that’s a hack with a ton of footguns built in. And in many cases, you can box those values. But that can be an awful perf trade off in a hot loop, which is (again IME) often exactly where nominal primitive types would be incredibly helpful.