Hacker News new | ask | show | jobs
by eyelidlessness 1614 days ago
The reason enums are useful—and the private keyword until recently with JS adding private fields—are that they’re nominal types. You can have…

  enum HTTPMethod {
    POST = 'post',
    // ...
  }

  enum FenceMaterial {
    POST = 'post',
    // ...
  }
… and you can be sure 'post' is not ambiguous.

Private fields have the same benefit, which is particularly useful for treating abstract classes as nominal interfaces. But yes, if your target environments support private fields natively, it’s more idiomatic to use those than the private keyword now.

I generally avoid namespaces, but they’re also sometimes useful eg satisfying weird function signatures expecting a callback with additional properties assigned to it. This is of course uncommon in TypeScript, but fairly common in untyped JavaScript and its corresponding DefinitelyTyped declarations.

2 comments

This is actually the reason I prefer string unions.

Lets say I have a function that converts sizes to pixels:

     const sizeToPx(size: ‘small’ | ‘med’ | ‘large’): number
If I have a Button component that can only be small or medium that’s no problem:

    type ButtonProps = { size: ‘small’ | ‘medium’ }
    const Button = styled.button(({ size }: ButtonProps) => ({
      height: sizeToPx(size)
I can’t do that with an enum.

You’re correct there’s a risk of a type collision. But I have never experienced anything like that. Seems pretty unlikely.

You can do that with an enum!

  enum Size {
    small = 'small',
    medium = 'medium',
    large = 'large',
  }

  type ButtonProps = { size: Size.small | Size.medium }
And it’s still a nominal type in the union.

Regarding likelihood of collision, it’s easy for me to imagine mixing up 'post' in an API call to a vendor for fence materials lol. In any case I find the added safety comforting, particularly over a language where interfaces tend to be exceedingly dynamic and flexible.

Namespaces are most useful for external typings, and in some cases are the only way to correctly model them, sadly