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

Type guard failures with negative condition #9861

Closed
falsandtru opened this issue Jul 21, 2016 · 3 comments
Closed

Type guard failures with negative condition #9861

falsandtru opened this issue Jul 21, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@falsandtru
Copy link
Contributor

falsandtru commented Jul 21, 2016

TypeScript Version: 2.0.0

Code

class A<T> {
  private _: T;
}
class B<T> {
  private _: T;
}
function f() {
  var o: A<void> | B<void> = new B<void>();
  if (!(o instanceof B)) return o; // B<void>, should be A<void>
  o; // B<any>, should be B<boid>
}

Expected behavior:

A type of o narrowed by type guard inside if statement is A<void>.
A type of o narrowed by type guard after if statement is B<void>.

Actual behavior:

A type of o narrowed by type guard inside if statement is A<void>.
A type of o narrowed by type guard after if statement is B<any>.

@yortus
Copy link
Contributor

yortus commented Jul 21, 2016

I think the 'problem' here is that you assigned a new B<void> instance in the declaration of o. TypeScript has accordingly narrowed o to B<void> for the rest of the function body.

To see the behaviour you are expecting, you can add an <any> cast to prevent the initial narrowing:

class A<T> {
  private _: T;
}
class B<T> {
  private _: T;
}
function f() {
  var o: A<void> | B<void> = <any> new B<void>();            // <=====
  if (!(o instanceof B)) return o; // A<void>, should be A<void>
  o; // B<void>, should be B<boid>
}}

@mhegazy
Copy link
Contributor

mhegazy commented Jul 22, 2016

@falsandtru i would appreciate it if you can limit the discussion to #9859 and avoid creating much noise.

@mhegazy
Copy link
Contributor

mhegazy commented Jul 22, 2016

This is the same topic discussed in #9859. closing in favor of #9859

@mhegazy mhegazy closed this as completed Jul 22, 2016
@mhegazy mhegazy added the Duplicate An existing issue was already created label Jul 22, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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

3 participants