[SOLVED] Vue 3: prop with Validator => TypeScript Error Claiming Other prop Does not Exist

Issue

In Vue (v3) adding a prop with a validator causes a TypeScript error claiming that another property does not exist. I have created a component illustrating the problem:

This works:

<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>

Now we add otherProp with a validator:

<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) // <- Problem occurs when
                               //    adding this line
    }
  },
  setup(props) {
    return {
      myComputed: computed(() => ('ABC_' + props.someProp + '_XYZ'))
      // Complains that `props.someProp` --^
      // is not defined here
    };
  }
});
</script>

We get an error with this 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 |   setup(props) {
    20 |     return {
  > 21 |       myComputed: computed(() => ('ABC_' + props.someProp + '_XYZ'))
       |                                                  ^^^^^^^^
    22 |       // Complains that `props.someProp` --^
    23 |       // is not defined here
    24 |     };

Using the computed object instead of the computed function in setup produces a similar result (then complaining that this.someProp does not exist, even though it does at runtime).

Why does this error occur? How could we have predicted this behaviour? Is validator still supported?

Current workaround: I dropped validator.

Solution

Add the type to the validator parameter :

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

Answered By – Boussadjra Brahim

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *