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.