7

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

2 Answers 2

19

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: "",
});
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use things: Array since that is also a function that returns an empty/new array
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.