Galivan
Galivan

Reputation: 5328

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>>'

Upvotes: 7

Views: 16695

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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:()=>[]
    }
})

Upvotes: 3

yoduh
yoduh

Reputation: 14659

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: "",
});

Upvotes: 18

Related Questions