Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Vue3's defineComponent function, the first generic parameter is Props, so I provide my props type using Typescript interface here. like:

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 };
  }
});

But my props are not identified by Vue, it means the code below won't work:

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

If I define props options in my components like:

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 };
  }
});

it will occurred type error TS2769: No overload matches this call. And I know if I remove the generic parameter will clean up this error, but the props options is not native Typescript.

Someone know how can I solve this?

like image 377
jctaoo Avatar asked Dec 31 '25 07:12

jctaoo


1 Answers

Props are a Vue runtime construct and can't be inferred from TypeScript type definitions (there are things like default values, validators, etc associated with props). You'll have to define them using the props option as the API expects. To provide strong type definitions for your props use PropType to annotate your props.

like image 197
Husam Ibrahim Avatar answered Jan 03 '26 10:01

Husam Ibrahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!