Skip to content

Modifier for bitflag enums #42521

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
DanielRosenwasser opened this issue Jan 27, 2021 · 3 comments
Open

Modifier for bitflag enums #42521

DanielRosenwasser opened this issue Jan 27, 2021 · 3 comments
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@DanielRosenwasser
Copy link
Member

DanielRosenwasser commented Jan 27, 2021

Consider the following code

export enum ScriptKind {
  Unknown = 0,
  JS = 1,
  JSX = 2,
  TS = 3,
  TSX = 4,
  External = 5,
  JSON = 6,
}

If a user tries to pass along the expression ScriptKind.JSX | ScriptKind.TSX to a parameter that expects a ScriptKind, then will end up constructing a value equal to ScriptKind.JSON.

Really, the user should have been told that this enum wasn't intended to be used in bitwise operations! But unfortunately, TypeScript doesn't catch this because you can assign any number to any numeric enum.

One could imagine a mode that prevents both the construction and the assignment for certain enums. In this mode, an enum has to be declared with the bitflags modifier if it wants to opt in to these types of bitwise operations, and to allow number to be assignable to that enum.

bitflags enum SymbolFlags {
    // ...
}

Alternatively, this could be something more akin to /** @deprecated */ or /** @internal */.

/// @bitflags
enum SymbolFlags {
    // ...
}

This is in some part inspired by Rust's bitflags macro.

@DanielRosenwasser DanielRosenwasser added In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Jan 27, 2021
@MartinJohns
Copy link
Contributor

MartinJohns commented Jan 27, 2021

This sounds like #21598.

@DanielRosenwasser
Copy link
Member Author

DanielRosenwasser commented Jan 27, 2021

It is pretty similar! The difference is that this modifier is really just a hint for some sort of strictness flag. It has no runtime impact.

@ShuiRuTian
Copy link
Contributor

I like this! I would try to give a prototype.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants