Skip to content

instanceof does not respect inherited Symbol.hasInstance #56536

Closed

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

Activity

  1. fatcerberus commented on Nov 25, 2023

    @fatcerberus

    does not respect inherited Symbol.hasInstance

    For the record, it actually works correctly with an inherited hasInstance:
    Playground link

    So the issue is specifically with intersections and generics.

  2. rotu commented on Nov 25, 2023

    @rotu
    Author

    Bruce Pascoe (@fatcerberus) well observed!

    Also broken with unions:

    const Top = {[Symbol.hasInstance]:(x:unknown)=>(true as const)}
    const Bot = {[Symbol.hasInstance]:(x:unknown)=>(false as const)}
    
    // broken
    function myInstanceOf(x:unknown, c : typeof Top | typeof Bot)
    {
      return x instanceof c
    }

    Workbench Repro

  3. added
    Needs Investigation
    on Nov 27, 2023
  4. added
    Fix Available
    on Mar 1, 2024
  5. removed
    Needs Investigation
    on Oct 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Fix Available

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions