更严格的对象文字赋值和联合类型

时间:2016-02-23 14:13:34

标签: typescript typescript1.6

自TypeScript 1.6起,有Stricter object literal assignment

但正如我所知,它不适用于联合类型。

module Test {
interface Intf { name: string; }

function doWorkWithIntf(param: Intf) {}
function doWorkWithUnionType(param: Intf | string) {}

function doWork2() {
    //doWorkWithIntf({name: "", xx: 10}) // does not compile TS2345
    doWorkWithUnionType({name: "", xx: 10}) // do compile
}
}

是我的错误还是编译错误? 我使用TS 1.7.5

1 个答案:

答案 0 :(得分:2)

最新版本的编译器肯定会捕获这个,但不是1.8.0或更低版本。

该功能仍然存在,例如:

var example: Intf = { name: '', xx: 10 };

无法在1.8.0中编译。但是,您的版本需要更多推理,并且看起来旧编译器不会解压缩联合类型以检查值。

您可以在TypeScript playground ...

上看到处理简单和复杂的案例
module Test {
    interface Intf { name: string; }

    function doWorkWithIntf(param: Intf) {}
    function doWorkWithUnionType(param: Intf | string) {}

    function doWork2() {
        //doWorkWithIntf({name: "", xx: 10}) // does not compile TS2345
        doWorkWithUnionType({name: "", xx: 10}) // do compile
    }


    var inf: Intf = { name: '', xx: 10 };
}
相关问题