简体   繁体   English

更严格的对象文字分配和联合类型

[英]Stricter object literal assignment and union types

Since TypeScript 1.6 there is Stricter object literal assignment 从TypeScript 1.6开始,有更严格的对象文字分配

But as i can see, it's not working with union types. 但正如我所见,它不适用于联合类型。

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
}
}

Is it my error or compiler bug ? 是我的错误还是编译器错误? I use TS 1.7.5 我使用TS 1.7.5

The very latest version of the compiler definitely catches this, but not 1.8.0 or below. 编译器的最新版本肯定可以解决此问题,但1.8.0或更低版本没有。

The feature still exists, for example: 该功能仍然存在,例如:

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

Will not compile in 1.8.0. 将不会在1.8.0中编译。 However, your version requires a little more inference, and it doesn't appear that the older compiler will unpack the union type to check the value. 但是,您的版本需要更多的推断,而且较旧的编译器似乎不会解压缩并列类型以检查该值。

You can see both the simple and the complex case being handled on the TypeScript playground ... 您可以在TypeScript操场上看到正在处理的简单案例和复杂案例。

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 };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM