The problem of parameter default in props,must is Arrow function,otherwise will get ts error
Version
3.2.31
Reproduction link
Steps to reproduce
<template>
<div></div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
components: {},
props: {
initValue: {
type: Object,
default() {
return {}; // It cannot be written as an ordinary function, or it will report a type error.
},
},
},
setup(props) {
/**
* TS2339: Property 'initValue' does not exist on type 'Readonly<LooseRequired<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions<Data>>>> &
* { [x: string & `on${string}`]: ((...args: any[]) => any) | ((...args: unknown[]) => any) | undefined; }>>'.
*/
const formData = ref({ ...props.initValue });
console.log(formData);
return {};
},
});
</script>
What is expected?
use arrow funtion but no ts error。i see Official website document props default is use Arrow function,but i use Arrow function ,is get ts error
What is actually happening?
TS2339: Property 'initValue' does not exist on type 'Readonly<LooseRequired<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions>>> & { [x: string & on${string}
]: ((...args: any[]) => any) | ((...args: unknown[]) => any) | undefined; }>>'.
If you replace it with an ordinary function, you will not report TS error
props: {
initValue: {
type: Object,
default: () => {}, // is it no get ts error
},
},
Try:
props: {
initValue: {
type: Object,
default: () => ({}),
},
},
In JavaScript, () => {}
is a function which returns undefined
, because the {}
is an empty function block. When you want to return an empty object {}
, use:
props: {
initValue: {
type: Object,
default: () => { return {} },
},
},
OR
props: {
initValue: {
type: Object,
default: () => ({}),
},
},
This behavior is documented and not really avoidable due to some TS limitations:
This behavior is documented and not really avoidable due to some TS limitations:
thank you,and here's the answer: https://v3.cn.vuejs.org/guide/typescript-support.html#%E6%B3%A8%E8%A7%A3-props https://vuejs.org/guide/typescript/options-api.html#typing-component-props