array.map中缺少返回类型

时间:2019-05-15 08:22:47

标签: typescript eslint

我在以下TypeScript代码中收到了Eslint警告:

“ function.eslint(@ typescript-eslint / explicit-function-return-type)上缺少返回类型。”警告是指map函数中的lambda。

private headerSelectionChanged(event): void {
    const { checked } = event.syntheticEvent.target;
    const newGridData = this.props.gridData.map(item => Object.assign(item, { selected: checked }));
    this.updateGridData(newGridData);
}

怎么了?我该如何解决?

2 个答案:

答案 0 :(得分:1)

显示警告,因为您的映射函数未指定返回类型。您必须这样指定返回类型:

const newGridData = this.props.gridData.map((item): any => Object.assign(item, { selected: checked }));

请记住,Object.assign会修改目标,而不是复制目标。如果您不希望修改this.props.gridData,则应交换item{ selected: checked }

const newGridData = this.props.gridData.map((item): any => Object.assign({ selected: checked }, item));

或使用较新的object spread operator(如果有):

const newGridData = this.props.gridData.map((item): any => ({ ...item, selected: checked }));

答案 1 :(得分:0)

尝试添加类似的类型:

private headerSelectionChanged(event: any): void {
const { checked } = event.syntheticEvent.target;
const newGridData = this.props.gridData.map((item: any) => Object.assign(item, { selected: checked }));
this.updateGridData(newGridData);

}