如何在Vue3(TypeScript)中定义Props?

3
在Vue3的defineComponent函数中,第一个泛型参数是Props,因此我在这里使用Typescript interface提供了我的props类型。示例如下:
export default defineComponent<{ initial?: number }>({
  setup(props) {
    const count = ref(props.initial ?? 0);
    const increase = () => count.value++;
    const decrease = () => count.value--;
    return { count, increase, decrease };
  }
});

但我的 props 并未被 Vue 识别,这意味着下面的代码将无法正常工作:

<Counter :initial="5"></Counter>

如果我像这样在组件中定义props选项:

如果我在组件中这样定义props选项:

export default defineComponent<{ initial?: number }>({
  props: {
    initial: { type: Number, required: false },
  },
  setup(props) {
    const count = ref(props.initial ?? 0);
    const increase = () => count.value++;
    const decrease = () => count.value--;
    return { count, increase, decrease };
  }
});

会发生类型错误:TS2769: No overload matches this call。 我知道如果我删除泛型参数,将清除此错误,但是选项属性不是本机TypeScript。

有人知道我该如何解决这个问题吗?

1个回答

2

Props是Vue的运行时构造,无法从TypeScript类型定义中推断出(与props相关的有默认值、验证器等内容)。您必须使用props选项进行定义,因为API需要。要为您的props提供强类型定义,请使用PropType注释您的props


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接