Hacker News new | ask | show | jobs
by erikpukinskis 1613 days ago
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.

1 comments

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.