Closed
Description
Suggestion
🔍 Search Terms
includes
, enum
(#46085 is relevant but not what this is discussing)
✅ Viability Checklist
My suggestion meets these guidelines:
- 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 feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
Array.prototype.includes
should be able to narrow down on a union of enum types instead of throwing:
TS2345: Argument of type 'SomeEnum | SomeOtherEnum' is not assignable to parameter of type 'SomeEnum'. Type 'SomeOtherEnum.C' is not assignable to type 'SomeEnum'.
📃 Motivating Example
export enum SomeEnum {
A = 'aaa',
B = 'bbb'
}
export enum SomeOtherEnum {
C = 'ccc',
D = 'ddd'
}
function someFunction(somePossibleValue: SomeEnum | SomeOtherEnum) {
if (Object.values(SomeEnum).includes(somePossibleValue)) { // <--- Includes signature should be changed so this narrow the type at compile time
return 'some result'; // <--- Inside the if-body, the type of somePossibleValue should be successfully narrowed down
}
if (Object.values(SomeOtherEnum).includes(somePossibleValue)) { // <--- Includes signature should be changed so this narrow the type at compile time
return 'some other result'; // <--- Inside the if-body, the type of somePossibleValue should be successfully narrowed down
}
throw new Error('On neither'); // <--- I understand this cannot be figured out at compile time because .includes cannot execute at compile time
}
💻 Use Cases
Allowing checks on something that could be possibly one of multiple enums.