Subscribe on changes!

The problem of parameter default in props,must is Arrow function,otherwise will get ts error

avatar
Apr 20th 2022

Version

3.2.31

Reproduction link

github.com

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
    },
  },
avatar
Apr 20th 2022

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: () => ({}), 
    },
},
avatar
Apr 20th 2022

This behavior is documented and not really avoidable due to some TS limitations:

https://vuejs.org/guide/typescript/options-api.html#caveats