When merging multiple prop definitions using Object.assign in defineProps, Vue props can be made optional

I have defined a const called MODAL_OPTION_PROP to set common props for a modal:

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

I am trying to use it in a modal component with defineProps

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

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

However, I am getting a not assignable warning 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 like currentItem is becoming optional. Is there a way to prevent this unexpected behavior?

Answer №1

In my previous response, I suggested using the spread operator instead of Object.assign.

const properties = defineProps(
  {
    ...MODAL_SETTINGS_PROP,
    selectedOption: {
      type: Object as PropType<Setting>,
      required: true,
    },
  }
)

Although I'm not entirely certain about the distinction, it seems that defineProps functions more like a macro rather than a regular function. This could be why it struggles with parsing complex expressions such as Object.assign.

Answer №2

A more streamlined approach would be:

const properties = generateProperties(
  defineProps<{
    modalSettings?: ModalConfiguration;
    selectedObject: Object;
  }>(),
  {
    modalSettings: DEFAULT_MODAL_SETTINGS,
  }
);

const editedObject = reference(properties.selectedObject);

Avoiding the use of Object.assign altogether.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with TypeScript Optional Parameters functionality

I am struggling with a situation involving the SampleData class and its default property prop2. class SampleData { prop1: string; prop2: {} = {}; } export default SampleData; Every time I attempt to create a new instance of SampleData without sp ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

Is there a way to execute a method from a child component in VueJS?

I'm trying to figure out how to make a parent component trigger a method in a child component when a button is clicked. Here's an example of what I have: Parent <template> <child-component></child-component> <button @clic ...

Exploring the dynamic loading of components within routes

Just starting out with Vue and experimenting with vue-router, I'm trying my hand at dynamically loading components without relying on additional libraries like webpack. So far, I've set up an index page and a router. Upon initial page load, I not ...

The function createVNode does not exist in the context of Vue integrated with Laravel

I've been attempting to replicate a component rendering based on an online example. While it works smoothly in a sample project, it crashes when applied to the official codebase. Here is the content of the blade file being rendered: <html lang=&q ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

"Can you explain how to utilize getter and setter with v-model in Vue.js

<div id="app"> <input v-model="msg"/> <p>{{ msg }}</p> </div> <script> class A{ } A.a = 1 new Vue({ el: '#app', data: { }, computed: { msg: { cache: false, set: function(val){ ...

Confusion surrounding the concept of returning an arrow function from a Vuex storage getter

I delved into a Vuex course and the journey was smooth sailing until they introduced an arrow function in a getter, then utilized it in a computed property and action. Behold the code: item structure: const _products = [ { id: 1, title: "iPad 4 Mini", ...

Is there a specific side effect that warrants creating a new Subscription?

Recently, I had a discussion on Stack Overflow regarding RxJS and the best approach for handling subscriptions in a reactive application. The debate was whether it's better to create a subscription for each specific side effect or minimize subscriptio ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...

Attempting to limit entry to a pathway when the loggedIn criterion is satisfied

I am currently facing a challenge with restricting access to the login page if the user is already logged in. I have been attempting to achieve this by checking for an existing token in the localStorage. Do you have any suggestions on how I can troublesh ...

Is it possible for me to incorporate a portion of the interface?

Is it possible to partially implement an interface? export interface AuthorizeUser { RQBody: { login: string; password: string; }; RSBody: { authorizationResult: AuthorizationResult; }; }; class AuthorizeUserRQBody implements Authorize ...

Having difficulty importing the WebRTCAdaptor from the antmedia package stored in the node modules directory into an Angular Typescript file

An error is appearing indicating that: There seems to be a problem finding a declaration file for the module '@antmedia/webrtc_adaptor/js/webrtc_adaptor.js'. The file 'D:/web/node_modules/@antmedia/webrtc_adaptor/js/webrtc_adaptor.js' ...

vue.js libs requiring "new ..." are being scolded by eslint for their misspelling

When working with Vue libraries, such as Swiper, that require the use of 'new …' in the script section, I encounter ESlint errors no matter how I try to write it. Even though 'new ...' works perfectly fine in the frontend, ESlint cont ...

Exploring the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array. A ...

Guide on building a Vue3 component with TypeScript, Pug Template engine, and Composition API

Whenever I try to export components within <script setup lang="ts"> and then use them in <template lang="pug">, an error is thrown stating that the component is defined but never used. Here's an example: <template la ...

The Microsoft.Azure.WebJobs.Script encountered an issue while attempting to cast an object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest' during the return process

I recently encountered an issue with my Azure Function written in JS that is triggered by the Service Bus and generates files to Blob Storage. When attempting to return an HTTP result, I received the following error message: System.Private.CoreLib: Except ...

From integrating Vue 2 TSX to React TSX: ensuring seamless cooperation

Currently, my app is built with Vue 2 using vue-tsx-support, vue-class-component, and vue-property-decorator. All of my Vue 2 components are already TSX classes. I am interested in gradually transitioning to React. I experimented with https://github.com/ ...

Encountering difficulties when attempting to inject NotifierService into an Angular Service

I am attempting to incorporate Angular NotifierService into my service class so that I can display error notifications in case of any exceptions from the service side. I attempted to inject a bean of NotifierService in the constructor of my service class, ...