镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Type guard failures with negative condition #9861

Description

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>.

Activity

  1. yortus commented on Jul 21, 2016

    @yortus
    Contributor

    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>
    }}
  2. mhegazy commented on Jul 22, 2016

    @mhegazy
    Contributor

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

  3. mhegazy commented on Jul 22, 2016

    @mhegazy
    Contributor

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

  4. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions