Skip to content

Type guard fails to narrow type with generic parameters #1943

Closed
@hesselink

Description

@hesselink

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?

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