Skip to content

Type guard fails to narrow type with generic parameters #1943

Closed

Description

The following code type checks:

class C
{
    foo: number;
}
function foo (x : C | Array<C>) : C
{
    if (x instanceof C)
      return x;
    return x[0];
}

However, if we add a type parameter to C, the following fails:

class C<A>
{
    foo: A;
}
function foo<A> (x : C<A> | Array<C<A>>) : C<A>
{
    if (x instanceof C)
      return x;
    return x[0];
}

There is an error on line 8 (return x;):

Type 'C<A> | C<A>[]' is not assignable to type 'C<A>'. Type 'C<A>[]' is not assignable to type 'C<A>'. Property 'foo' is missing in type 'C<A>[]'.

I've tried a couple of other things, but can't get this to type check. Is this a bug, or am I missing an obvious solution?

Activity

  1. mhegazy commented on Mar 24, 2015

    @mhegazy
    Contributor

    looks like the same issue in #2388

  2. locked and limited conversation to collaborators on Jun 18, 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