【发布时间】:2017-10-25 07:48:45
【问题描述】:
在下面的代码中,我预计 TypeScript 编译器在 getThings_concat 和 getThings_nocats 上都会失败,但它只会抱怨后者:
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() 返回非IThings 时它会抱怨?
【问题讨论】:
-
你为什么写
[].concat?concat不会改变原始数组;你可以放心地写things1().concat(things2())。或者直接写[...things1(), ...things2()]。 -
@RyanCavanaugh 我不喜欢
things1().concat(things2())的可读性(它让things1看起来很特别。最后一个要好得多,谢谢。
标签: arrays typescript interface concat