microsoft / microsoft/TypeScript

Modifier for bitflag enums

Open
#42,521 3 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files, tests, or entry points are specified. Start by reviewing the proposed bitflags modifier and the alternative annotation, then define the intended construction, assignment, and bitwise-operation rules; done means one design is selected with corresponding diagnostics and enum semantics agreed.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.