union type inference change between v1.7 and v1.8

44 Views Asked by At

In snippet below TypeScript compiler v1.7 identifies x as C1 under third typeguard clause

class C1 { item: string }
class C2 { item: string[] }
class C3 { item: string }

function Foo(x: C1 | C2 | C3): string {
    if (x instanceof C1)
        return x.item;
    else if (x instanceof C2)
        return x.item[0];
    else if (x instanceof C3)
        //in v1.7 compiler thinks x is C1 
        //in v1.8 compiler thinks x is C2 
        return x.item;
} 

V1.8 thinks of x as C2 under third typeguard therefore making compilation to fail. Is it intended or bug?

1

There are 1 best solutions below

0
On

This is a bug in the compiler both in v1.7 and v1.8 even though the final result is different in them. The (x instanceof C3) type guard should make it C3 in that block period. I'll log a bug.

Bug report : https://github.com/Microsoft/TypeScript/issues/7271