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