typescript - array.map 中缺少返回类型

标签 typescript eslint

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

“function.eslint(@typescript-eslint/explicit-function-return-type) 上缺少返回类型”警告引用了映射函数中的 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);
}

出了什么问题?我该如何修复它?

最佳答案

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

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

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

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 }));

关于typescript - array.map 中缺少返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144677/

相关文章:

json - 如何提示我无法控制的函数类型?

javascript - 如何使用附加接口(interface)定义通用 HOC 以添加到 props

typescript - 无法在 Typescript 中导入 svg.js

typescript - 为什么类型 "never"在联合类型中毫无意义?

javascript - 使用 Sequelize 在多个表之间创建 "Many to Many"关系

eslint - 如何禁用有关一些未使用参数的警告,但保留 "@typescript-eslint/no-unused-vars"规则

javascript - 使用 ESLint 修复 WebStorm 中的标记区域

typescript - Typescript 用户定义类型/对象的数组作为 Lit v2 中的属性

reactjs - 当需要函数内具有动态路径的文件时,如何修复 eslint 失败?

javascript - ESLint:防止在 Javascript 中使用箭头函数(我从小就称它们为 Lambda 函数)