更严格的对象字面量赋值和联合类型
Stricter object literal assignment and union types
从 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.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 };
}
从 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.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 };
}