how to compile time check strongly typed props in vue templates?

浪子不回头ぞ 提交于 2021-02-08 05:33:02

问题


Using Vue with Typescript makes it possible to specify types for props: Strongly typing props of vue components using composition api and typescript typing system

However, as far as I can see these props are only checked at runtime. Here's a simple example component. It has two props a, and b. One is a number and the other a string. Additionally b has a validator, it is only valid if it's 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>

Here's how you could (incorrectly) use the component. The prop a has a wrong type and the prop b fails its validation:

<TestComp a="hi" b="ho"/>

Is it possible to find this bug at compile time? Out of the box, Vue only complains at runtime, with a message such as Invalid prop: custom validator check failed for prop "b".

After searching online, I found that prop type validation can be switched on as an experimental Vetur feature. But this doesn't call the custom validator, so in the example above, Vetur can't find the problem for b.
Also, I'm not always using Vetur and would prefer to have the wrong types trigger an actual compile time error.

来源:https://stackoverflow.com/questions/64623971/how-to-compile-time-check-strongly-typed-props-in-vue-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!