slackapi / node-slack-sdk

Slack Developer Kit for Node.js
https://slack.dev/node-slack-sdk
MIT License
3.26k stars 656 forks source link

types 3.0: discuss continued use of string literals/unions vs. switching to enums #1817

Open filmaj opened 3 weeks ago

filmaj commented 3 weeks ago

This issue comes out of #1227 and has one example of the suggestion to replace unions with enums in the draft PR #1228 (in this commit specifically).

The purpose of this issue is first as a discussion starting point to debate which approach we should use to model specific lists of constants. To date we have used string literals and unions of them, but the suggestion that @raycharius proposed in #1227 and #1228 was to move to enums.

I found this post debating the pros and cons of using string literals/unions over enums to be enlightening. It is a worthwhile read and after considering it, I think I also side with the author and consider the benefits of string literals/unions to outweigh the benefits of enums. The fact that enums also contribute to increased bundle size is a downside that should not be ignored. Finally, the technique of using string arrays with as const in order to seamlessly convert runtime code into compile-time code is a great technique that we should use!

const directionsAsString = ["up", "down", "left", "right"] as const;
// union derived from runtime value
type Direction = typeof directionsAsString[number];
//   ^? type Direction = "up" | "down" | "left" | "right"
console.log(
  `The following are valid directions to move your player: ${directionsAsString
    .join(", ")
    .trim()}`
);

So my own preference would be to stick with string literals and unions over enums, but I wanted to give space to the community to voice their own preferences.