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

Broken instanceof type guarding #17424

Closed
nin-jin opened this issue Jul 26, 2017 · 5 comments
Closed

Broken instanceof type guarding #17424

nin-jin opened this issue Jul 26, 2017 · 5 comments
Labels
Duplicate An existing issue was already created

Comments

@nin-jin
Copy link

nin-jin commented Jul 26, 2017

TypeScript Version: 2.4.0

Code

class A { foo: string }
class B { bar: string }

function test(x : A | B) {
  if (x instanceof A) {
    console.log(x.foo);
  } else {
    console.log(x.bar); // Expected typeof x == A|B
  }
}

test({ foo: "Hello, world" }); // undefined

Expected behavior:

Error at this line:

    console.log(x.bar);

Because x can implement A (and not implement B) interface but do not be instance of A class.

Actual behavior:

No errors. Wrong result.

@nin-jin nin-jin changed the title Broken instanceof type guarging Broken instanceof type guarding Jul 26, 2017
@ikatyang
Copy link
Contributor

Duplicate of #17344

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Jul 28, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Aug 17, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Aug 17, 2017
@nin-jin
Copy link
Author

nin-jin commented Aug 17, 2017

My issue is not about nominal typing. My issue is about wrong logic. If x is instance of class A, then x implements interface A. But if x is not instance of A, then x can implement and can implement not interface A. Be attentive!

https://en.wikipedia.org/wiki/Set_theory

@mhegazy
Copy link
Contributor

mhegazy commented Aug 17, 2017

@nin-jin, you are correct, except that most uses of this pattern assume that A and B are disjoint, and a check for inclusion in A implicitly checks for exclusion from B . you can see more about the rational for the current design in #1719 (comment)

@nin-jin
Copy link
Author

nin-jin commented Aug 17, 2017

In most uses else block assume that B is any. Why you broke logic for incorrect uses? You will take more and more issues about it until fix it.

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants