Skip to content

Disallow bitwise operators with different const enum types #61760

Open
@u130b8

Description

@u130b8

πŸ” Search Terms

const enum bitwise and operator flags bitfields

βœ… Viability Checklist

⭐ Suggestion

Bitwise operations on const enums should only allow using values of same const enum type.

πŸ“ƒ Motivating Example

const enum EnumA {
  Left  = 1 << 0,
  Right = 1 << 1
}

const enum EnumB {
  Top    = 1 << 0,
  Bottom = 1 << 1,
  Left   = 1 << 2,
  Right  = 1 << 3
}

let border = EnumB.Left;

// Good: Cannot assign a different enum
// @ts-expect-error
border = EnumA.Left;

// Bad: Can use bitwise AND with different enum
if (border & EnumA.Left) {
  console.log("Bug due to typo: Actually wanted EnumB");
}

πŸ’» Use Cases

  1. What do you want to use this for?
    Avoid typo mistakes in code.
  2. What shortcomings exist with current approaches?
    Right now bitwise operations are unchecked (while assignment is checked), allowing typo mistakes like above.
  3. What workarounds are you using in the meantime?
    Being careful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions