Vue in conjunction with Typescript enables the specification of types for props, allowing for more robust component development. For example, check out this discussion on Strongly typing props of vue components using composition api and typescript typing system
However, it seems that these prop type checks only occur at runtime. Let's consider a simple component with two props: a
, and b
. One is expected to be a number while the other should be a string with a specific validation condition (i.e., equal to hi
)
<template>
<p>{{a}}</p>
</template>
<script>
import {defineComponent} from 'vue';
export default defineComponent(
{
name: "TestComp",
props:{
a:number,
b:{
type: String,
validator:(val)=>val=="hi"
}
}
}
)
</script>
Visualize the misuse of this component where a
has an incorrect type and b
fails its validator:
<TestComp a="hi" b="ho"/>
The question arises: can we detect such bugs during compile time rather than waiting for runtime errors? By default, Vue only raises an error at runtime when encountering invalid props, displaying messages like
Invalid prop: custom validator check failed for prop "b"
.
After some online research, I stumbled upon an experimental Vetur feature that allows for prop type validation. However, this feature does not trigger the custom validator, hence missing issues similar to the one observed in prop b
above.
Moreover, relying solely on Vetur may not be ideal as I prefer immediate compile-time errors for wrong prop typings.