简体   繁体   中英

Stricter object literal assignment and union types

Since TypeScript 1.6 there is Stricter object literal assignment

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

The very latest version of the compiler definitely catches this, but not 1.8.0 or below.

The feature still exists, for example:

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

Will not compile in 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 ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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