在下面的代码,我希望打字稿编译器失败在两个getThings_concat
和getThings_nocats
但它只是抱怨后者:为什么TypeScript在从concat构建时不会抱怨数组的类型?
interface IThing {
name: string;
}
function things1() {
return [
{name: 'bob'},
{name: 'sal'},
]
}
function things2() {
return [
{garbage: 'man'},
]
}
function getThings_concat():Array<IThing> {
return <Array<IThing>>([].concat(things1(), things2()));
}
function getThings_nocats():Array<IThing> {
let ret:Array<IThing> = [];
things1().forEach(thing => {
ret.push(thing);
});
things2().forEach(thing => {
ret.push(thing);
});
return ret;
}
下面是一个编译器错误,但我期望两个错误(一个用于各getThings_*
功能):
test.ts(24,18): error TS2345: Argument of type '{ garbage: string; }' is not assignable to parameter of type 'IThing'.
Property 'name' is missing in type '{ garbage: string; }'.
我能在getThings_concat
改变,这样我可以使用[].concat
但它抱怨时things2()
返回非IThing
S'
为什么你要写'[] .concat'? 'concat'不会改变原始数组;你可以安全地写'things1()。concat(things2())'。或者只写'[... things1(),... things2()]'。 –
@RyanCavanaugh为了可读性,我不喜欢'things1()。concat(things2())'(它使'things1'看起来很特别,最后一个更好,谢谢。 – iffy