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

Type guards don't work for interfaces with only optional properties #5842

Description

For some reason type guards to not work if an interface has only optional properties.

interface A {
  foo : number;
}

function isA(object: any): object is A {
  return true;
}

let a: A | boolean;

if (isA(a)) {
  a.foo;   // compiles
}



interface B {
  foo? : number;
}

function isB(object: any): object is B {
  return true;
}

let b: B | boolean;

if (isB(b)) {
  b.foo;  // does not compile because type inference says its `B | boolean`
}

Activity

  1. mhegazy commented on Dec 1, 2015

    @mhegazy
    Contributor

    For a type guard, it will look through all the union type constituents (B and boolean in the example), and will filter out types that are not assignable to the target type. since B has only optional properties, booelan is assignable to, and it is not filtered out from the union. looks like a good candidate for #3842.

    a work around is to tag type B, see #4895

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

    By DesignDeprecated - use "Working as Intended" or "Design Limitation" instead

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions