Bring in properties from a separate file in Vue3

Currently, I am utilizing Vue3 along with the options API. Within my setup, there are various Vue components that rely on a shared prop defined as:

  exercise: {
    type: Object as PropType<Exercise>,
    required: true,
  },

To streamline this process and avoid redundant declarations of the same prop in multiple components, I decided to consolidate these shared props into an object named sharedProps, which can then be imported across components:

export const sharedProps = {
  exercise: {
    type: Object as PropType<Exercise>,
    required: true,
  },

However, upon importing and using sharedProps within a component like so:

props: {
   // component-specific props ...
   ...sharedProps
}

I encountered an issue where accessing this.exercise in my component code resulted in its type being inferred as Exercise|undefined, despite having required: true set for the corresponding prop.

This error was not only flagged by my IDE but also caused build process failures.

Interestingly, when I directly add the prop to the component without importing it, its type is correctly recognized as Exercise.

Furthermore, I observed that providing a default value to the prop resolved the issue. However, based on my understanding, setting required: true should suffice in indicating it as a non-optional property.

Why does this behavior occur specifically when importing props from an external file?

Answer №1

Agreed, @Estus Flask is absolutely correct!

<script lang="ts">
import { defineComponent, PropType } from "vue";
type Exercise = {
  day: number
}
const commonProps = {
  exercise: {
    type: Object as PropType<Exercise>,
    required: true as const,
  },
}

export default defineComponent({
  props: {
    time: String,
    ...commonProps
  }
})
</script>
<template>
  <h1>{{ exercise.day }}</h1>
</template>

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

Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend. The error is being c ...

The application within the Main Module is not being acknowledged by the other components within the module

I am facing an issue with my AngularJS application where the directive I created within the 'FormTest' module is not recognizing the variable 'app' even though it is defined within the same module. The error message I receive is TS2304 ...

Error Type: Jest: A transform is required to have a `process` function in order for it to

Encountering an error while running 'npm test': FAIL __tests__/unit/domain/services/demo-service.ts ● Test suite failed to run TypeError: Jest: a transform must export a `process` function. at ScriptTransformer._getTransformer ( ...

leveraging services in Angular 4's router system

Below is the route setup: export const routes: Routes = [ {path: '', redirectTo: '/login', pathMatch: 'full'}, {path: 'login', component: LoginComponent, canActivate: [dbs.ConfigGuard]}, {path: '**& ...

Dealing with nullable properties in Typescript

In my React Component code snippet, I am facing an issue with an optional field that needs to be initialized as undefined. This is causing difficulties when trying to use it after type checking. The problem arises in the context of using typescript version ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

What is the most effective method for transferring and accessing data within a child form component?

This is how I am currently handling it: Parent.vue: // Template <form-child :schema="schema"><form-child> // JS data () { return { schema: [{ // name: '', value: '', type: '' }, { //etc ... }] } } For ...

Error: Module not found - Issue with importing SVG files in NextJS

Currently, I am utilizing the babel plugin inline-react-svg to import inline SVGs in NextJS. Here is a snippet from my .babelrc configuration file: { "presets": ["next/babel"], "plugins": [ "inline-react-svg" ...

Insufficient column height when using CSS flex-grow property

I am facing an issue with my 3 flex columns that have varying text lengths, resulting in uneven heights. I have tried using flex-grow: 1; to make them match in height, but it does not seem to be working as intended. Can someone please help me identify what ...

Is it possible to make changes to Vue data within a function while in the process

Recently delving into the world of VueJs, I find myself navigating through laravel 6.0. While grappling with the concept of variable scopes in javascript, I sense there might be a missing piece in this puzzle. It's interesting to note that when I pla ...

Obtain the appropriate selection in the dropdown based on the model in Angular

I am working on a dropdown menu that contains numbers ranging from 1 to 10. Below is the HTML code for it: <div class="form-group"> <label>{{l("RoomNumber")}}</label> <p-dropdown [disab ...

The parameter of type '{ userInfo: string | null; }' cannot be assigned to type 'never' in this argument

Currently, I am working on creating a context API in React using TypeScript to store user details and tokens. Since I am relatively new to TypeScript, I am facing some challenges understanding the errors below. Can someone please assist me with this? ..... ...

Is it possible to enhance an interface by integrating the characteristics of a constant?

I am currently working on customizing a material-ui v4 Theme. Within our separate @our-project/ui package, we have the following: export declare const themeOptions: { palette: { // some colors missing from Palette } status: string; // other pro ...

Visibility issue with CKEditor5 in VueJS

I am facing a challenge with creating a component that displays CKEditor allowing me to write Markdown content. Despite the presence of HTML code in the DOM, the CKEditor itself is not visible on the frontend: <div style="display: none;">& ...

Utilizing vue-i18n within Class-based Components in Vue 3

Currently, I am in the process of migrating from vue2 to vue3 and using the "Class Style Component". I have been utilizing vue-i18n. Will I be able to continue using vue-i18n with Vue3? Here is a snippet from my package.json: "dependencies": ...

Nuxt - Pausing for a moment after running an asynchronous action with this.$store.dispatch

I'm currently navigating through the world of Nuxt and encountering a puzzling issue. If I input the following code: const resp1 = await this.$axios.$post('urlCall1', {...dataCall1}); this.$axios.$post('urlCall2', {...dataCall2, r ...

PageObjectModel Playwright, execute the locator().all() function - 'The execution context has been terminated, possibly due to navigating to another...'

Hey there, I'm currently working on a basic test using POM. Here is a snippet from one of my PageObjects Class: import { Expect, Page, Locator } from "@playwright/test"; export class InventoryPage { readonly page: Page; readonly addToC ...

Guide to validating a form using ref in Vue Composition API

Incorporating the Options API, I implemented form validation in this manner: template: <v-form ref="form" v-model="valid" lazy-validation @submit.prevent> ... script: methods: { validate() { this.$refs.form.validate(); ...

Best practices and distinctions when it comes to typing in TypeScript functions

Do the typings below differ in any way, or are they essentially the same with personal preference? interface ThingA{ myFunc(): number; } interface ThingB{ myFunc: () => number; } ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...