Vue 3 + TypeScript中setup脚本导入使用共享props的正确方式是什么?
Vue 3
<script setup> 共享props的正确实现方案 报错原因
你当前的写法报错是因为直接给共享props变量标注了ComponentObjectPropsOptions类型,该类型内部依赖了Vue未公开导出的私有类型PropOptions,Rollup等工具做类型导出/检查时就会触发私有名称的报错。同时直接使用该通用类型会丢失你定义的每个prop的精确类型信息,也会导致IDE类型提示、静态检查工具失效。
解决方案1:运行时配置+类型保留方案(推荐)
该方案可以复用props的运行时校验规则,同时兼容所有官方工具链:
第一步:修改共享props定义文件
// sharedProps.ts import type { ComponentObjectPropsOptions, ExtractPropTypes } from 'vue' // 使用satisfies约束配置格式符合要求,同时保留原始对象的精确类型 const sharedProps = { modelValue: { type: String, default: '', }, id: { type: String, default: null, }, } satisfies ComponentObjectPropsOptions // 可额外导出对应的TS类型,方便其他地方复用类型声明 export type SharedPropsType = ExtractPropTypes<typeof sharedProps> export default sharedProps
第二步:组件中使用(和你原有写法一致,无需修改)
<script setup lang="ts"> import { defineProps } from 'vue' import sharedProps from '@/props/sharedProps' const props = defineProps({ ...sharedProps, label: { type: String, default: '', }, }) // 此时props的类型会被正确推导,包含共享props和自定义props的所有字段 </script>
解决方案2:纯类型共享方案
如果你不需要复用props的运行时校验规则,只需要复用类型定义,可以直接用接口继承的方式实现:
第一步:定义共享props类型
// sharedProps.ts export interface SharedProps { modelValue?: string id?: string }
第二步:组件中使用
<script setup lang="ts"> import { defineProps, withDefaults } from 'vue' import type { SharedProps } from '@/props/sharedProps' // 继承共享类型,扩展当前组件的独有props interface Props extends SharedProps { label?: string } // 定义props,搭配withDefaults设置默认值 const props = withDefaults(defineProps<Props>(), { modelValue: '', id: null, label: '' }) </script>
以上两种写法都是Vue官方支持的标准用法,兼容Volar、VueDX、Rollup、Vite等所有主流工具链,不会出现类型报错问题。
内容的提问来源于stack exchange,提问作者Willow
相关产品推荐
相关产品推荐

