TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Detect no overlap for "in" keyword

Open StevenBrons opened this issue 7 months ago • 1 comments

🔍 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/)

StevenBrons avatar Jun 15 '25 15:06 StevenBrons

This is intentional, as objects are not sealed. They may contain more properties than the type specifies.

Duplicate of #50953.

MartinJohns avatar Jun 15 '25 17:06 MartinJohns

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

typescript-bot avatar Jun 19 '25 01:06 typescript-bot