vue3中props的定义方式是什么(Typescript)

What's the way to define props in vue3 (Typescript)

在Vue3的defineComponent函数中,第一个通用参数是Props,所以我在这里使用Typescript接口提供我的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 };
  }
});

但是我的道具没有被 Vue 识别,这意味着下面的代码不起作用:

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

如果我在我的组件中定义道具选项,例如:

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。

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

道具是 Vue 运行时构造,不能从 TypeScript 类型定义中推断出来(默认值、验证器等与道具相关联)。您必须按照 API 的预期使用 props 选项来定义它们。要为您的道具提供强类型定义,请使用 PropTypeannotate your props.