为什么 TypeScript 在从 concat 构建时不抱怨数组的类型?
Why doesn't TypeScript complain about an array's type when built from concat?
在下面的代码中,我希望 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()
returns 不是 IThing
时它会抱怨?
通过将 []
的类型从 any[]
更改为 IThing[]
:
,这会给您带来预期的错误
function getThings_concat():Array<IThing> {
return (<IThing[]>[]).concat(things1(), things2());
}
不过,最好直接这样写函数,不需要任何类型断言
function getThings_concat2():Array<IThing> {
return [...things1(), ...things2()];
}
在下面的代码中,我希望 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()
returns 不是 IThing
时它会抱怨?
通过将 []
的类型从 any[]
更改为 IThing[]
:
function getThings_concat():Array<IThing> {
return (<IThing[]>[]).concat(things1(), things2());
}
不过,最好直接这样写函数,不需要任何类型断言
function getThings_concat2():Array<IThing> {
return [...things1(), ...things2()];
}