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

Vite React项目中使用TypeScript遇到类型错误求助

解决Vite React+TypeScript项目中的类型错误

针对你遇到的两个错误,这里给出具体修复方案:

错误1:Type 'Element' is missing the following properties from type 'ReactElement ': type, props, key

问题根源是你导入并使用了JSX.Element作为组件返回类型。在React+TypeScript的规范中,正确的组件返回类型应为React.ReactElement,或者你可以直接省略返回类型(TypeScript会自动完成类型推断)。

修改App组件的返回类型:

import React from "react";
import TodoList from "./components/TodoList";

// 方式1:使用React.ReactElement指定返回类型
function App(): React.ReactElement {
    const todos = [{id: 1, text: "Finish the course"}]
    return (
        <div>
            <h1>Hello world</h1>
            <TodoList items={todos}/>
        </div>
    )
}

// 方式2:省略返回类型,TypeScript自动推断
// function App() {
//     const todos = [{id: 1, text: "Finish the course"}]
//     return (
//         <div>
//             <h1>Hello world</h1>
//             <TodoList items={todos}/>
//         </div>
//     )
// }

export default App

错误2:Property 'h1' does not exist on type 'JSX.IntrinsicElements'

这个错误通常是TypeScript未正确识别JSX全局类型,或tsconfig.json配置异常导致的,按以下步骤排查:

  • 确认依赖安装:
    虽然Vite创建React+TS项目时会自动安装类型依赖,但可重新安装确保完整性:

    npm install @types/react @types/react-dom --save-dev
    
  • 检查tsconfig.json配置:
    确保compilerOptions中的jsx字段设置为react-jsx(适配React 17+的自动JSX转换模式):

    {
      "compilerOptions": {
        "jsx": "react-jsx",
        // 其他配置项...
      }
    }
    

    该配置会让TypeScript自动处理JSX,无需手动导入React中的JSX类型。

  • 移除冗余导入:
    你之前代码中导入的{ JSX } from "react"在React 17+自动转换模式下完全多余,直接删除即可。

额外优化:TodoList组件类型定义

为让TodoList的items属性类型更严谨,建议给组件定义Props类型:

// components/TodoList.tsx
import React from "react";

// 定义单个Todo项的类型
interface Todo {
  id: number;
  text: string;
}

// 定义组件Props类型
interface TodoListProps {
  items: Todo[];
}

export default function TodoList({ items }: TodoListProps) {
  return (
    <ul>
      {items.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

这样App组件中的todos会自动匹配类型,避免潜在的类型错误。

内容的提问来源于stack exchange,提问作者Jože Kuhar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:53:23