Skip to content

TS enforces left-hand side of instanceof must be an object type, but it can be any type.Β #59492

Closed
@voliva

Description

@voliva

πŸ”Ž Search Terms

"instanceof", "Symbol.hasInstance"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about instanceof

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.5.4#code/FAYw9gdgzgLgBAUQG4FMIDkCuBbARigJyjgF44BvYOOAbQGUBPPMAGwDoALAQygEloYXCCBQBdAFxwAFEklCGASlIA+ODAYAHFGABmcJKRJkA5BBz4CxuADJr+uAFI4AJkNwADMAC+AbmDAASz0pAGY4AIEhEV1EVAxzQiglSmpwaFYUNhYwAHMpY2wODjgAd24YAH5jBW9-IOkARndwyOFtPWQ0LDxE5Ko4NKgMrNypACIm8OIUOLGar2AgA

πŸ’» Code

const EvenNumbers = {
  [Symbol.hasInstance]: v => typeof v === 'number' && v % 2 == 0
};

if (3 instanceof EvenNumbers) {
  console.log('mhh what?')
}

if (10 instanceof EvenNumbers) {
  console.log("10 is even")
}

πŸ™ Actual behavior

Typescript shows an error on the 3 and the 10:

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

πŸ™‚ Expected behavior

It should not show any error, because the code is valid JS

Additional information about the issue

After having support for hasInstance #55052, this actually means that the left-hand side operand doesn't have to be an object anymore. It can perfectly be primitives, as shown by this example (albeit contrieved...)

The spec for relational expressions also allows any kind of relational expressions (which also includes anything that resolves in a primitive) as well https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-relational-operators

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions