Vue3 can accept a prop of type String or PropType

In my Vue3 project, I have a component that accepts a prop which can be either a string or an object. Here's how it looks:

import { defineComponent } from 'vue'

const Component = defineComponent({
  props: {
    book: {
      type: [String, Object]
    }
  }
})

If the prop is an object, I want to specify a type for it as shown in the Vue3 documentation:

import { defineComponent, PropType } from 'vue'

interface Book {
  title: string
  year?: number
}

const Component = defineComponent({
  props: {
    book: {
      type: Object as PropType<Book>
    }
  }
})

My challenge is how to combine both scenarios, like this (which currently doesn't work):

import { defineComponent, PropType } from 'vue'

interface Book {
  title: string
  year?: number
}

const Component = defineComponent({
  props: {
    book: {
      type: [String, Object as PropType<Book>]
    }
  }
})

Answer №1

Try using a function expression for the prop type like this:

const Component = defineComponent({
  props: {
    movie: {           👇
      type: [String, () => Object as PropType<Movie>]
    }
  },
  mounted() {
    const isMovie = (obj: any): obj is Movie => 'title' in obj // eslint-disable-line @typescript-eslint/no-explicit-any

    if (isMovie(this.movie)) {
      console.log(this.movie.title)
    }
  }
})

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

How can I make v-for display additional profiles to achieve an infinite scroll effect?

Hey there! I've got a Firestore database set up to fetch profiles and display them on a page using v-for. I want to implement infinite scroll for a smoother user experience. Here's the JavaScript composable code I'm working with: import { pr ...

Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this: var data = [ { student: "sam", English: 80, Std: 8 }, { student: "sam", Maths: 80, Std: 8 }, { student: "john", English: 80, Std: 8 }, { student: "j ...

The 'XXX' property is not found in 'YYY' type but is necessary in 'ZZZ' type

I'm struggling with setting up class properties in TypeScript. Here is the TypeScript code that I am working on: export class myClass { a: number; b: number; public getCopy(anotherClass: myClass): myClass { return { a: anotherClass.a, ...

The Vue Js modal is having a quirk where it opens upon clicking but refuses to

view-more.vue: <template> <div id="app"> <button type="button" class="btn btn-primary" v-on:click='DisplayModal'> Show </button> <div class="card" v-show="ModalStatus"> <div class="card-header"> This is the ...

The cookieconsent package's buttons are unresponsive in a Vue.js environment

I have integrated a cookie consent feature in my Vue application. I've included the cookieconsent package: import cookieconsent from "cookieconsent"; Vue.use(cookieconsent); In App.vue, I have initialized it: created() { this.cookiesC ...

Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8. The employee-list component is responsible for presenting data in a table format. Within the employee-list.component.ts file, I have defined: import { Component } from '@angular/core'; impo ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

Angular 2: Obtaining the caret position in a contenteditable 'div'

Take a look at this code snippet: <div #test (click)="onClick(test)" contenteditable="true"> This text can be edited by the user. </div> @ViewChild('test') el:ElementRef; constructor(private elementRef: ElementRef) {} ...

Error encountered when attempting to use Gridsome for Vue.js project construction

Currently, I am utilizing Vue.js and Gridsome to craft a personalized portfolio. However, an issue arose when I attempted to incorporate a JSON file to store my profile details on the site. Here is how I imported the file within my Index.vue component: &l ...

The error message "Ionic 3 encountering issues with accessing property 'valid' from undefined or null reference"

As I was setting up a form on a CRUD using Firebase, initially just storing name and number as string types, I decided to add more parameters of the same type. However, I encountered an issue with the error message "Unable to get property 'valid' ...

Troubleshooting Cross-Origin Resource Sharing Problem in Vue.js Single Page Application and Node.js API

My Node.js Express app is set up with the cors npm package installed. Additionally, there is basic authentication enabled on the nginx server hosting my Node.js app (authentication requires an 'Authorization' key in the headers of each request). ...

Can the GitHub URL be utilized for installing TypeScript npm dependencies?

When working with an npm library written in TypeScript, the usual process involves writing the source code in TypeScript, pushing it to GitHub, then converting it to JavaScript and pushing the resulting JavaScript code to the npm repository. When adding ...

When attempting to modify the state in a parent component from a child using the composition API in Vue 3, the error "this.$emit() is not a

//Main component <template> <childComponent @onChangeData='updateData' /> </template> <script> setup() { const state = reactive({ data: 'example' }); function updateData(newValue){ s ...

Is there a way to customize the slicing of *ngFor in a component according to the components it is being injected into?

This code snippet represents a component that needs to be included in other components: <div class="row"> <div class="col-12 [...]" *ngFor="let course of courses"> <div class="card"> ...

Guide to returning a watcher in a global function with Vue 2

Hey there, I'm facing an issue in my code. In main.js, I have a global function called getSites, which is essential for fetching a list of sites from an API asynchronously using async/await. To manage the asynchronous data retrieval process, I' ...

Troubleshooting the issue with mocking the useTranslation function for i18n in JEST

Currently, I am facing an issue with my react component that utilizes translations from i18next. Despite trying to create tests for it using JEST, nothing seems to be getting translated. I attempted to mock the useTranslation function as shown below: cons ...

Intellisense in VSCode is failing to suggest subfolder exports

In my setup, I have a repository/module specifically designed to export TypeScript types into another project. Both of these projects are using TypeScript with ECMAScript modules. The relevant part of the tsconfig.json configuration is as follows: "ta ...

Is it possible to loop through each row in a table using Cypress and execute the same actions on every iteration?

I have a frontend built with html/typescript that features a table of variable length containing action buttons in one of the columns. I am looking to create a Cypress test that will click on the first button of the first row, carry out a specific task, an ...

Can you explain the distinction between Array<string> and string[]?

Can you explain the contrast between Array<string> and string[]? var companies: Array<string> = ['Samsung', 'Sony', 'LG']; var businesses: string[] = ['Lenovo', 'Asus', 'Acer']; ...

Issue with iview-ui: Unable to make admin panel full height. The iView example suggests using min-height: 200px

Is there a reason why the iView admin template can only scale to a preset height? Can someone assist me in setting the height of the admin to fill the entire browser (100vh or 100%)? Many thanks in advance. The example on the site displays a predefined m ...