【问题标题】:Why doesn't TypeScript complain about an array's type when built from concat?为什么 TypeScript 从 concat 构建时不抱怨数组的类型?
【发布时间】:2017-10-25 07:48:45
【问题描述】:

在下面的代码中,我预计 TypeScript 编译器在 getThings_concatgetThings_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 时它会抱怨?

【问题讨论】:

  • 你为什么写[].concatconcat 不会改变原始数组;你可以放心地写things1().concat(things2())。或者直接写[...things1(), ...things2()]
  • @RyanCavanaugh 我不喜欢things1().concat(things2()) 的可读性(它让things1 看起来很特别。最后一个要好得多,谢谢。

标签: arrays typescript interface concat


【解决方案1】:

通过将[] 的类型从any[] 更改为IThing[],这将为您提供您所期望的错误:

function getThings_concat():Array<IThing> {
    return (<IThing[]>[]).concat(things1(), things2());
}

不过最好这样简单地编写函数,不需要任何类型断言

function getThings_concat2():Array<IThing> {
    return [...things1(), ...things2()];
}

【讨论】:

  • 好的,我以为我正在更改 [] 的类型,但现在我发现我可能只是在转换 concat 的结果?无论如何,最后一种语法更好。谢谢!
猜你喜欢
  • 2021-06-27
  • 2017-02-09
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2019-06-04
  • 1970-01-01
相关资源
最近更新 更多