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/react | jsx: 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 支持泛型类型定义
📝 发现内容有误?点击此处直接编辑