You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript中forEach报错:Type 'void'不可分配给'ReactNode'

问题

练习时将代码写在App.tsx中,调用函数出现错误。原本以为array.map()在TypeScript中可正常使用,但用forEach生成的HTMLElement未在页面显示,同时触发TypeScript错误:"Type 'void' is not assignable to type 'ReactNode'.ts(2322)"。

相关代码:

import * as React from 'react';

export default function KeyLists() {
  let keyList = ['a', 'b', 'c']
  return (
    <div>
      {keyList && keyList.forEach((key)=>{
        <li>{key}</li>
      })} // 此处VSCode有警告
    </div>
  )
}

TypeScript提示信息:

Type 'void' is not assignable to type 'ReactNode'.ts(2322)
index.d.ts(1421, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

package.json内容:

{
  "private": true,
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start",
    "typecheck": "tsc",
    "lint-fix": "eslint --fix './{lib,src,test}/**/*.{ts,tsx}' && prettier --write './{lib,src,test}/**/*.{ts,tsx}'"
  },
  "dependencies": {
    "@emotion/react": "^11.11.1",
    "@emotion/styled": "^11.11.0",
    "@mui/icons-material": "^5.14.8",
    "@mui/material": "^5.14.8",
    "classnames": "^2.3.1",
    "date-fns": "^2.28.0",
    "gray-matter": "^4.0.3",
    "microcms-js-sdk": "^2.5.0",
    "next": "latest",
    "prettier": "^3.0.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "remark": "^14.0.2",
    "remark-html": "^15.0.1",
    "sass": "^1.66.1",
    "typescript": "^4.7.4"
  },
  "devDependencies": {
    "@types/node": "^18.0.3",
    "@types/react": "^18.0.15",
    "@types/react-dom": "^18.0.6",
    "@typescript-eslint/eslint-plugin": "^6.6.0",
    "@typescript-eslint/parser": "^6.6.0",
    "autoprefixer": "^10.4.7",
    "eslint": "^8.49.0",
    "eslint-config-prettier": "^9.0.0",
    "eslint-plugin-react": "^7.33.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "postcss": "^8.4.14",
    "tailwindcss": "^3.1.4"
  }
}

解决方案

错误核心原因

  • forEach方法的返回值是void,而React要求组件子元素必须是ReactNode类型,因此TypeScript会抛出类型不匹配的错误。
  • 即便忽略类型错误,forEach仅遍历执行回调逻辑,不会返回任何元素,所以页面不会渲染出<li>节点。

修复代码

将forEach替换为map(map会返回新数组,符合React对子元素的要求),同时给每个列表项添加唯一key属性,并且用<ul>包裹<li>以符合HTML规范:

import * as React from 'react';

export default function KeyLists() {
  const keyList = ['a', 'b', 'c'];
  return (
    <div>
      <ul>
        {keyList.map((key) => (
          <li key={key}>{key}</li>
        ))}
      </ul>
    </div>
  );
}

额外优化点

  • 把let改为const:keyList不会被重新赋值,使用const更符合TypeScript最佳实践。
  • 移除keyList &&判断:空数组调用map会返回空数组,React会自动处理这种情况,无需额外判断。

内容的提问来源于stack exchange,提问作者Halkichi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:10:34