2
<script lang="ts" setup>   
  interface Props {
    bigArray: string[];
  }
        
  ***const props = withDefaults(defineProps<Props>(), {
    bigArray:[],
  }*** <---- Here is the error, setting props
        
  const bigArray = ref(props.BigArray);
</script>

ITsInterface.ts

BigArray?: string[] | null;

Looking for the proper way to set up an empty array as a prop in this scenario:

  • Vue.js3
  • composition API
  • TypeScript
  • setup in script tag

2 Answers 2

11
import { withDefaults, defineProps} from "vue";

interface Props {
    bigArray?: string[]
}

const props = withDefaults(defineProps<Props>(), {
    bigArray: () => []
})

console.log(props.bigArray);

You just needed to add the () => arrow-function for it to work.

This is shown here in the vue documentation.

And if you want to make the prop optional (as it should be with a default value) use ? after the variable-name. This will ensure there are no unnecessary warnings in the console.

Sign up to request clarification or add additional context in comments.

2 Comments

I was looking for a solution to have a prop with multiple products but when there are no products i want a default array. Not sure why but adding '() => [],' instead of '[]' fixed the issue. type PropTypes = { products: Product[], } const props = withDefaults(defineProps<PropTypes>(), { products: () => [], });
@Whitespacecode so my solution works? - if so feel free to upvote the answer, or do you need any further assistance?
-1

As shown in the vue documentation here.

You could do it like that:

const props = defineProps({
  bigArray: {
    type: Array,
    default: []
  }
});

This defines a prop with the name bigArray and sets the default to an empty array.

2 Comments

I appreciate the feedback, but the prop has been set as a type: string previous in the interface
@randomfool yeah i know - i thought you just need one option. Didn't know you want/need the interface - will take a further look at this later

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.