Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

P.instanceOf doesn't resolve ptototype chain #164

Open
maximri opened this issue Jun 6, 2023 · 0 comments
Open

P.instanceOf doesn't resolve ptototype chain #164

maximri opened this issue Jun 6, 2023 · 0 comments

Comments

@maximri
Copy link

maximri commented Jun 6, 2023

Describe the bug
seems like P.instanceOf doesn't resolve prototype chain when inheritance doesn't add anything

class GrandParentClass {
  private doesNotHelpToAddSomething = "soTsPatternCanDifferBetweenInstances";
  constructor(public message: string) {
    this.message = message;
  }
}
class UncleClass extends GrandParentClass {
  // private helpsToAddSomething = "soTsPatternCanDifferBetweenInstances";
}
class ParentClass extends GrandParentClass {
  // private helpsToAddSomething = "soTsPatternCanDifferBetweenInstances";
}

class ChildClass extends ParentClass {}

const instance: GrandParentClass = new ParentClass("!");

// it resovles to never after ChildClass .with unless we add 'helpsToAddSomething' to ParentClass
// if adding 'helpsToAddSomething' only to Parent than Uncle is resolved but Parent is still never
const res = match(instance)
  .with(P.instanceOf(ChildClass), (e) => `this is Child${e.message}`)
  .with(
    P.instanceOf(UncleClass),
    (e) => /*e is never*/ `this is Uncle${e.message}`
  )
  .with(
    P.instanceOf(ParentClass),
    (e) => /*e is never*/ `this is Parent${e.message}`
  )
  .run();

//  wiil output: 'this is Parent!'
console.log(res);

js instaceof does look at the prototype correctly

// will output 'instance is instanceof ParentClass'
if (instance instanceof ChildClass) {
  console.log("instance is instanceof ChildClass");
} else {
  if (instance instanceof UncleClass) {
    console.log("instance is instanceof UncleClass");
  }
  if (instance instanceof ParentClass) {
    console.log("instance is instanceof ParentClass");
  } else {
    if (instance instanceof GrandParentClass) {
      console.log("instance is instanceof GrandParentClass");
    }
  }
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

Code Sandbox with a minimal reproduction case
https://codesandbox.io/s/ts-pattern-instanceof-not-resolving-bwmk5d?file=/src/index.ts

Versions

  • TypeScript version: 4.9.4
  • ts-pattern version: 4.3.0
  • environment: node 18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant