Detect no overlap for "in" keyword
🔍 Search Terms
"in keyword", "no overlap"
✅ Viability Checklist
- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x] This wouldn't change the runtime behavior of existing JavaScript code
- [x] This could be implemented without emitting different JS based on the types of the expressions
- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
⭐ Suggestion
Extend the "This comparison appears to be unintentional because the types have no overlap" error to the in keyword.
📃 Motivating Example
When you compare values with types that have no overlap, e.g. in the following example:
const a = "foo";
const b = "bar";
if (a === b) {
}
We get the nice error message This comparison appears to be unintentional because the types '"foo"' and '"bar"' have no overlap.(2367).
The same does unfortunately not hold for the in keyword, which is sometimes confused when used in combination with arrays:
const a = "foo";
const b = ["foo"] as const;
if (a in b) {
}
(for those that fall in the trap, the in keyword compares the keys of ["foo"], so 0, length etc.)
It would be a logical extension of the other error to also include this case.
💻 Use Cases
As highlighted above, the current behavior leaves errors on the table that should be fixed. Workarounds can be achieved using linting (gpt believes https://typescript-eslint.io/rules/no-unnecessary-condition/)
This is intentional, as objects are not sealed. They may contain more properties than the type specifies.
Duplicate of #50953.
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.