Vue中Object.assign合并defineProps定义时必填Prop变可选的解决方法
解决Vue中合并Props后必填项被识别为可选的TypeScript问题
问题原因
使用Object.assign合并通用Props和自定义必填Props时,TypeScript无法正确识别defineProps中currentItem的required: true约束——因为Object.assign返回的是普通Object类型,丢失了Vue Prop定义的元信息推导能力,导致currentItem被错误标记为Item | undefined。
解决方案
方案1:用对象展开语法替代Object.assign
直接通过ES6对象展开语法合并Props定义,defineProps能正确解析Prop元信息,TypeScript也能准确推导类型:
const props = defineProps({ ...MODAL_OPTION_PROP, currentItem: { type: Object as PropType<Item>, required: true, }, }); const editingItem = ref<Item>(props.currentItem);
方案2:显式定义Props类型接口(严谨TypeScript写法)
通过定义包含通用和自定义Props的接口,作为defineProps的泛型参数强制约束类型:
import type { PropType } from 'vue'; // 通用Props类型 interface ModalCommonProps { modalOption: ModalOptionParams; } // 组件自定义Props类型,继承通用Props interface ItemModalProps extends ModalCommonProps { currentItem: Item; } const props = defineProps<ItemModalProps>({ ...MODAL_OPTION_PROP, currentItem: { type: Object as PropType<Item>, required: true, }, }); const editingItem = ref<Item>(props.currentItem);
方案3:将通用Props封装为函数返回(可选)
如果通用Props需要复用且保持类型推导,可以封装成函数返回字面量对象:
export const getModalOptionProp = () => ({ modalOption: { type: Object as PropType<ModalOptionParams>, default: DEFAULT_MODAL_OPTION, }, }); // 组件中使用 const props = defineProps({ ...getModalOptionProp(), currentItem: { type: Object as PropType<Item>, required: true, }, });
内容的提问来源于stack exchange,提问作者Sibevin Wang
相关产品推荐
相关产品推荐

