Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set array as default value on props (Vue composition api + Typescript)

With Vue 3 (composition api) + Typescript , I am trying to set default values on the props after defining them with an interface. I get a typescript error when I try to set default value [] on one of the props. How can I set a default empty array?

<script setup lang="ts">

interface IProps {

  title: string;
  things: any[];
  productUrl: any;
}

const props = withDefaults(defineProps<IProps>(), {
  title: "",
  things: [],            //<-- error (se below)
  productUrl: "",
});

The error:

Type 'never[]' is not assignable to type '(props: Readonly<IProps>) => any[]'.

It also says:

The expected type comes from property 'things' which is declared here on type 
'InferDefaults<Readonly<IProps>>'
like image 558
Galivan Avatar asked Jul 12 '26 02:07

Galivan


2 Answers

Object or array prop defaults must be returned from a factory function. The Vue docs mention this under prop validation

const props = withDefaults(defineProps<IProps>(), {
  title: "",
  things: () => [],
  productUrl: "",
});
like image 146
yoduh Avatar answered Jul 13 '26 15:07

yoduh


You should return the empty array using a function :

<script setup lang="ts">

interface IProps {

  title: string;
  things: any[];
  productUrl: any;
}

const props = withDefaults(defineProps<IProps>(), {
  title: "",
  things: ()=>[], 
  productUrl: "",
});

For the standard syntax :

const props =defineProps({
  things:{
      type:Array,
      required:true,
      default:()=>[]
    }
})
like image 28
Boussadjra Brahim Avatar answered Jul 13 '26 17:07

Boussadjra Brahim



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!