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

Discriminated union not discriminated when the union type is produced by a type guard #19904

Description

TypeScript Version: 2.7.0-dev.20171110

Code

// two types discriminated by boolean tag
type Foo = {isFoo: true, foo: string};
type Bar = {isFoo?: false, bar: string};

type Union = Foo | Bar;

declare const a: Union;

// works as expected
if (a.isFoo) {
  a.foo;  // ok
  a.bar;  // error
} else {
  a.foo;  // error
  a.bar;  // ok
}

// doesn't work inside type guard though
type Any = {isFoo?: boolean};
declare function isUnion(t: Any): t is Union;

declare const b: Any;
if (isUnion(b)) {
  // b is Union
  if (b.isFoo) {
    b.foo;  // error
    b.bar;  // error
  } else {
    b.foo;  // error
    b.bar;  // error
  }
  
  // works with newly assigned variable
  const c = b;
  if (c.isFoo) {
    c.foo;  // ok
    c.bar;  // error
  } else {
    c.foo;  // error
    c.bar;  // ok
  }
}

Expected behavior:

Should work the same way with narrowed type.

Actual behavior:

Discriminating between the union members doesn't work inside the type guard. strictNullChecks is enabled.

Activity

  1. mhegazy commented on Jul 18, 2018

    @mhegazy
    Contributor

    narrowing occurs only on variables that are declared to be of union type. in this case, b is declared to have a non-union type, and thus is excluded. c has a union type also, by virtue of being assigned to from b after the type guard has been applied.

  2. typescript-bot commented on Jul 31, 2018

    @typescript-bot
    Contributor

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

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

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions