microsoft / microsoft/TypeScript

Allow primitive LHS to `instanceof` operator if RHS is a custom `hasInstance`

Open
#63,219 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

### 🔎 Search Terms

in:title instanceof

### 🕗 Version & Regression Information

- This changed between versions 5.2 and 5.3
- This changed in commit or PR #55052

### ⏯ Playground Link

https://www.typescriptlang.org/play/?#code/IwAglgdgzgLghhAxgUwPYDMQG8QG0DKAngLYBGqANgHQAWcUAktPEsgLoAUAlNiAE7IYAVz4QQMPkOQgAvjICwAKAD0ykAD0QAFRrSKydDAC0dCABMQUMGekYQCEAHJIsBCgyOQyAB4AHAVBWqGLEQrAgpLaYMIS+0o4IhI4ANPZiqKQAVsiIMOKxtnz2+XEgvnB8cMSCyHxUHABMAMwArAAcXEA

### 💻 Code

```ts
1 instanceof { [Symbol.hasInstance]() { return true }}
```

### 🙁 Actual behavior

Error: The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.(2358)

### 🙂 Expected behavior

No errors

### Additional information about the issue

For custom 'Symbol.hasInstance' methods, `number instanceof obj` can return true or false according to implementation.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground reproduction and compare the reported behavior for `1 instanceof { [Symbol.hasInstance]() { return true }}` with the expected result. Trace the type-checking path for `instanceof` expressions, then add coverage showing that a primitive left-hand side is accepted when the right-hand side defines a custom `Symbol.hasInstance`.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.