-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Open
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
π Search Terms
const enum bitwise and operator flags bitfields
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β 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
- What do you want to use this for?
Avoid typo mistakes in code. - What shortcomings exist with current approaches?
Right now bitwise operations are unchecked (while assignment is checked), allowing typo mistakes like above. - What workarounds are you using in the meantime?
Being careful.
Metadata
Metadata
Assignees
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript