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

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.


I 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


I 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.


I 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!


Private fields, unique symbols, there's many ways to do nominal typing in TypeScript, depending on what you want.


I 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.


Why is nominal typing desirable?


example:

  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


To 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).


unless... you know




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

Search: