Skip to content

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

@filmaj

Description

@filmaj

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:typescriptissues that specifically impact using the package from typescript projectsauto-triage-skipdiscussionM-T: An issue where more input is needed to reach a decisionpkg:typesapplies to `@slack/types`semver:major

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions