0

在下面的代码片段中,TypeScript 编译器 v1.7 在第三个 typeguard 子句下将 x 标识为 C1

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 将 x 视为第三类型保护下的 C2,因此编译失败。是有意的还是错误的?

4

1 回答 1

1

这是v1.7 和 v1.8中编译器中的一个错误,即使它们的最终结果不同。(x instanceof C3)类型保护应该在C3那个块期间完成。我会记录一个错误。

错误报告:https ://github.com/Microsoft/TypeScript/issues/7271

于 2016-02-26T23:35:26.047 回答