Search code examples
typescriptvue.jsvue-props

Vue props become optional when using Object.assign to merge multiple prop definitions in defineProps


I use a const MODAL_OPTION_PROP to define common props for modal as below:

export const MODAL_OPTION_PROP = {
  modalOption: {
    type: Object as PropType<ModalOptionParams>,
    default: DEFAULT_MODAL_OPTION,
  },
};

And try to apply it in a modal component defineProps

const props = defineProps(
  Object.assign({}, MODAL_OPTION_PROP, {
    currentItem: {
      type: Object as PropType<Item>,
      required: true,
    },
  })
);

const editingItem = ref<Item>(props.currentItem);

Then a not assignable warning occurs on props.currentItem:

(property) currentItem?: Item | undefined
Argument of type 'Item | undefined' is not assignable to parameter of type 'Item'.
  Type 'undefined' is not assignable to type 'Item'.ts(2345)

It seems that currentItem becomes optional. Are there any ways to avoid this unexpected behavior?


Solution

  • As I mentioned in the comment, you can use spread operator instead of Object.assign.

    const props = defineProps(
      {
        ...MODAL_OPTION_PROP,
        currentItem: {
          type: Object as PropType<Item>,
          required: true,
        },
      }
    )
    

    To be honest i'm not sure what's the difference, but i think it has something to do with defineProps being a macros rather than a function. It probably just can't parse complex expressions like Object.assign