在下面的代碼,我希望打字稿編譯器失敗在兩個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