全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-23 6 分钟 ✍️ juanwangdev

Vue/React 类型支持

配置框架组件的类型声明,使 TypeScript 正确识别和检查组件类型。

Vue 单文件组件类型

TypeScript
// vite-env.d.ts
/// <reference types="vite/client" />

declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent<object, object, unknown>
  export default component
}

Vue 组件类型定义

vue
<script setup lang="ts">
import type { PropType } from 'vue'

// 定义 props 类型
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  items: {
    type: Array as PropType<string[]>,
    default: () => []
  }
})
</script>

React JSX 类型

JSON
// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx"
  }
}

React 类型声明

Bash
npm add -D @types/react @types/react-dom

React 组件类型

tsx
import React from 'react'

interface Props {
  title: string
  count: number
}

const Component: React.FC<Props> = ({ title, count }) => (
  <div>
    <h1>{title}</h1>
    <p>{count}</p>
  </div>
)

JSX 工厂函数配置

JavaScript
// Vue JSX
export default defineConfig({
  esbuild: {
    jsxFactory: 'h',
    jsxFragment: 'Fragment'
  }
})

// React JSX
export default defineConfig({
  esbuild: {
    jsxFactory: 'React.createElement',
    jsxFragment: 'React.Fragment'
  }
})

类型声明对比

框架类型声明JSX 配置
Vue*.vue 模块声明jsxFactory: h
React@types/reactjsx: react-jsx

注意:Vue 3 推荐使用 定义组件类型。

Vue Props 类型推导

vue
<script setup lang="ts">
// 自动推导类型
const props = defineProps<{
  title: string
  count?: number
}>()

// 响应式 props
const { title } = toRefs(props)
</script>

要点总结

  • Vue 需声明 *.vue 模块类型
  • React 需安装 @types/react
  • jsx 配置控制 JSX 转译方式
  • defineProps 支持泛型类型定义

📝 发现内容有误?点击此处直接编辑

← 上一篇 强制重新预构建
下一篇 → TypeScript 配置优化
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库