New Vue 3 update: Validator in prop causes TypeScript error falsely claiming non-existent prop

When working with Vue (v3), I encountered an issue where adding a prop with a validator triggered a TypeScript error indicating that another property did not exist. To better illustrate the problem, I created a component:

The first version without any issues:

<template>
  <div>{{myComputed}}</div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';

export default defineComponent({
  name: 'MyComponent',
  props: {
    someProp: String
  },
  setup(props) {
    return {
      myComputed: computed(() => ('ABC_' + props.someProp + '_XYZ'))
    };
  }
});
</script>

Adding a new prop otherProp with a validator led to the following problematic version:

<template>
  <div>{{myComputed}}</div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';

export default defineComponent({
  name: 'MyComponent',
  props: {
    someProp: String,
    otherProp: {
      type: String,
      default: '',
      validator: (v) => (true)
    }
  },
  setup(props) {
    return {
      myComputed: computed(() => ('ABC_' + props.someProp + '_XYZ'))
    };
  }
});
</script>

This implementation resulted in the following cryptic error message:

ERROR in src/components/MyComponent.vue:21:50
TS2339: Property 'someProp' does not exist on type 'Readonly<LooseRequired<Readonly<{ [x: number]: string; } & { length?: number | undefined; toString?: string | undefined; toLocaleString?: string | undefined; concat?: string[] | undefined; join?: string | undefined; ... 17 more ...; flat?: unknown[] | undefined; }> | Readonly<...>>>'.
    19 |
    20 |     
  > 21 |       
       |                     ^^^^^^^^
    22 |       
    23 |       
    24 |     

The issue persists even when using the computed object instead of the function within the setup, posing a challenge around accessing this.someProp which seemingly does not exist during compilation.

What causes this error? Could we have foreseen this behavior? Is the use of validator still encouraged in Vue?

As a temporary fix, I decided to eliminate the validator altogether.

Answer №1

Include the data type in the validator value :

anotherProperty: {
  type: String,
  default: '',
  validator: (value:string) => (true)
                // ^-----------
}

Answer №2

If the previous method is not effective or doesn't meet your needs, you can try encapsulating your props within a defineProps function like this:

  props: defineProps({
    customProp: {
      type: String,
      default: '',
      validator: (value) => (true)
    }
  }),

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

Is there a way to optimize Typescript compiler to avoid checking full classes and improve performance?

After experiencing slow Typescript compilation times, I decided to utilize generateTrace from https://github.com/microsoft/TypeScript/pull/40063 The trace revealed that a significant amount of time was spent comparing intricate classes with their subclass ...

The icon is being displayed as text instead of the actual Fontawesome icon

Using jquery version 3.3.1 I am dynamically creating an anchor tag: let link = $("<a>"); link.attr("href", "#"); link.text("My anchor" + ' <i class="fas fa-people-carry"></i>'); However, when I try to display ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

I am encountering difficulty with importing this particular file

I am struggling to get this image to display on my webpage using React. Despite reading through the Facebook documentation, I am still unable to figure it out and feeling quite frustrated. Any help would be greatly appreciated. https://jsfiddle.net/gexcoz1 ...

What steps can be taken to restrict access to the next page for users who are not logged in?

In my main JavaScript file, I am trying to implement a condition where users must be logged in to access the welcome page. If a user is not logged in, they should be redirected to the login page by default. However, in my current code, the form is submitti ...

What are the ways in which I can utilize regular expressions to match multiple values?

I need help creating a regex pattern that will match the following sequence- +911111111111, +912222222222, +913333333333, +914444444444 This regex should only allow the characters "+" and numbers. My current attempt is: /^(\+91)\d{10}$/ How ...

Pagination in Datatables

Here is the code snippet I am working with: $('#ldap-users, #audit-users').dataTable({ "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p& ...

Having trouble formatting the date value using the XLSX Library in Javascript?

I'm having trouble separating the headers of an Excel sheet. The code I have implemented is only working for text format. Could someone please assist me? const xlsx = require('xlsx'); const workbook = xlsx.readFile('./SMALL.xlsx') ...

What is the significance of providing a sole argument to the Object () function?

Answering a related question about object constructors, what is the intention behind passing an argument to the constructor of objects and using it in this specific manner? function makeFoo(a, b) { var foo = Object.create(Foo.prototype); var res ...

How to tell if one mesh is contained within another in Three.js

Currently, I am experimenting with Three.js and trying to figure out a way to check if one mesh is completely contained within another mesh. I've created a small robot that moves around inside a home box controlled by the player. While I know how to d ...

Exploring the functionalities of Firebase's FirebaseListObservable alongside the powerful

How can I create an observable that depends on the value of another observable? It seems simple, but I can't figure out how to do it. user$: Observable<firebase.User>; playlists$: FirebaseListObservable<any>; constructor(db: AngularFireD ...

What is the best way to transform a string representation of data into an array and then showcase it in

After importing CSV data and converting it into the variable stringData, I am facing an issue when trying to display this data in a React table. Although I have attempted to use the map function to separate the headers and map to <th>, displaying t ...

Having trouble with playing audio from an array in Javascript

I've been working on creating a Drum Kit website. My approach involves using an array to hold all the sound files, and using a loop to call the play() function. However, I encountered an issue when trying to load the sounds - the debug console showed: ...

I am currently working with an input element that is set to hidden. I am trying to change its type to text using JavaScript, but I can't seem to figure out how to do it or if it is even possible

I'm stuck trying to change the type of an input element from hidden to text using JavaScript. I can't seem to figure out if it's even possible. Can someone please help me with this? Thanks! ...

Attempting to create a fresh string by substituting certain characters with different ones

Exploring TypeScript, I encountered a puzzle where I needed to substitute specific characters in a string with other characters. Essentially, replacing A with T, T with A, C with G, and G with C. The initial code snippet provided to me looked like this: e ...

Show a collection of files in a table format

Here is the current code I have: index.html <!DOCTYPE html> <html> ... </form> </div> </body> </html> And here is my code.gs function doGet() { return HtmlService.createHtmlOutputFromFile('index'); } ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

tips for showcasing individuals' information in the main content area

Hey everyone, I'm currently working on a mini application in react JS. In this application, I am looking to display data in the body section when a search is performed using a textbar. Can anyone provide some guidance on how I can achieve this or what ...

The elements within the NativeScript components are failing to show the data received from the Django API

My Django API is set up to provide a list of movies titles with their corresponding IDs. I've implemented a movie service in TypeScript that retrieves the list of movie titles and IDs using the GET operation. In my NativeScript project, I have two f ...

Transforming a text into a vNode in VueJS

I recently encountered a situation where I had a string stored in the database that looks something like this: Lorem #ipsum dolor sit amet, #consectetur adipiscing elit, sed do #eiusmod tempor incididunt ut labore et dolore magna aliqua. Within the string ...