Skip to content

instanceof does not respect inherited Symbol.hasInstance #56536

@rotu

Description

@rotu

🔎 Search Terms

hasinstance, instanceof, 2359, TS2359

🕗 Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play?declaration=false&target=9&module=7&ts=5.4.0-dev.20231124#code/C4TwDgpgBAEghgZwJIDsHDigxhA8gMygF4oBvAKCigG0BlEAWwCMB7AGwDoALRVdTHAF0AFAA8AXAFcUAaxQsA7igCU4qK3YRM5AL7lyAegNQWM8vmlZgASxYooDEHwzY8+MVNnylAGihZxeGQ0FxwCZQoqACcIYEko+1EoaxCBCBZCLF19I3Uo0wgUc0sbOwcnVNcCVGAIKIQIK1sUD2k5RRQ-AKDnNIIoADITJgArRuAIyigYuISoJJT+Vwz-bMNjJnyZQuLsUvtHXqr8AHFCuussAB4AYSgIUVqUABMEWF5KsPwAPlavDq64huk2isXiiWSn3SmV0QA

💻 Code

type HasInstanceOf = {
  [Symbol.hasInstance](x:unknown): boolean
}

// ok
function myInstanceOf(x:unknown, c:HasInstanceOf){
  return x instanceof c
}

// broken
function myInstanceOfIntersection(x:unknown, c:HasInstanceOf & object){
  return x instanceof c
}

// broken
function myInstanceOfGeneric<C extends HasInstanceOf>(x:unknown, c:C){
  return x instanceof c
}

🙁 Actual behavior

The second and third examples give error TS2359

The right-hand side of an 'instanceof' expression must be either of type 'any', a class, function, or other type assignable to the 'Function' interface type, or an object type with a 'Symbol.hasInstance' method.

In all cases, the right-hand side is an object type with a Symbol.hasInstance method.

🙂 Expected behavior

I expect all three examples to typecheck.

Additional information about the issue

No response

Metadata

Metadata

Assignees

Labels

Fix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions