Setting an array as the default value for props in Vue using the composition API and TypeScript

Incorporating Vue 3 along with the composition API and TypeScript, I am facing an issue setting default values for props defined through an interface. When attempting to set a default value of [] for one of the props, I encounter a TypeScript error. How can I successfully 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 (see below)
  productUrl: "",
});

The error message reads:

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

Additionally, it states:

The expected type comes from property 'things' which is declared here on type 
'InferDefaults<Readonly<IProps>>'

Answer №1

It is recommended to use factory functions to return defaults for object or array props. This information can be found in the Vue documentation section on prop validation

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

Answer №2

To implement a function that returns an empty array, follow this code:

<script setup lang="ts">

interface DataModel {

  name: string;
  items: any[];
  url: any;
}

const data = withDefaults(defineData<DataModel>(), {
  name: "",
  items: ()=>[], 
  url: "",
});

Using the standard syntax:

const data =defineData({
  items:{
      type:Array,
      required:true,
      default:()=>[]
    }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An easy guide on utilizing ngSwitch for datatype selection in Angular

While working in angular2, I came across a question regarding the usage of ngSwitch to load <div> tag based on the datatype of a variable. Is it possible to achieve something like this: <div [ng-switch]="value"> <p *ng-switch-when="isObj ...

Efficiently Measuring the Visibility Area of DetailsList in Fluent UI

I am currently utilizing the DetalisList component alongside the ScrollablePane to ensure that the header remains fixed while allowing the rows to scroll. However, I have encountered a challenge as I need to manually specify the height of the scrollable co ...

Disregard the opossum circuit breaker's HTTP 404 Error

I've been working on an express API and successfully incorporated a circuit breaker using opossum. Is there a way for the circuit breaker to handle custom HTTP exceptions generated by the application? I attempted to utilize the errorFilter option, b ...

Unsubscribing EventListener during ngOnDestroy

Here is my implementation of a directive in Angular. I am facing an issue with removing the event listener in this case: import { Directive, ElementRef, OnDestroy } from "@angular/core"; @Directive({ selector: "[Enter]" }) export class Enter implemen ...

Make sure all scenarios are accounted for in TypeScript union type switching

I have a union type defined as follows: type Action = 'foo' | 'bar' | 'baz'; I would like the compiler to throw an error if someone attempts to extend this type. Consider the code snippet below: type Action = 'foo&ap ...

Combining String Literal Types with a regular string type

Is there a way to utilize the intellisense feature of TypeScript for predefined colors in my component's prop, while still allowing users to input their own hex color codes? type PREDEFINED_COLORS = 'success' | 'error' | 'info ...

Enhancing JavaScript with TypeScript: implementing functional mixins

I'm in the process of creating functional mixins using TypeScript. Below is the code I have written so far: const flying = (o: object) => { let isFlying = false; return Object.assign({}, o, { fly() { isFlying = true; return thi ...

What could be causing this error when running nodemon in an Angular TS file?

One issue I am facing is that upon running the npm run dev command, I encounter the error message stating that 'node_modules is not recognized as an internal or external command'. Here is an image showing the specific error: https://i.sstatic.ne ...

Generating Components Dynamically in Angular 4 Based on User-Defined Input

I am interested in developing an innovative App using Angular 4 that enables the creation of components from various storage sources such as database, URLs, and server-stored files. The main objective is to allow users to design their own components for pe ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

Warning: Unhandled promise rejection detected

I'm encountering an issue with Promise.reject A warning message pops up: Unhandled promise rejection warning - version 1.1 is not released How should I go about resolving this warning? Your assistance is greatly appreciated public async retrieveVe ...

Conceal the header on signup and login pages using Material UI

I am working on a project with three pages: SignUp, Login, and Lists, along with a header component. My goal is to hide the header on the SignUp and Login pages, and only show it on the List page. Any suggestions on how I can achieve this? Here is my cod ...

Instructions on transferring information from the app.component to its child components

I am currently working with Angular 6 and I have a specific requirement. I need to send data retrieved from an external API in my app.component to other child components. Instead of repeatedly calling the common API/service in every component, I want to ma ...

Tips for creating consecutive HTTP API requests in Angular 2

Is there a way to use RXJS in order to handle multiple API calls, where one call is dependent on another? ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

What are the repercussions of labeling a function, TypeScript interface, or TypeScript type with export but never actually importing it? Is this considered poor practice or is there a potential consequence?

I find myself grappling with a seemingly straightforward question that surprisingly has not been asked before by others. I am currently immersed in a TypeScript project involving Vue, and one of the developers has taken to labeling numerous interfaces and ...

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

What is the recommended data type for the component prop of a Vuelidate field?

I'm currently working on a view that requires validation for certain fields. My main challenge is figuring out how to pass a prop to an InputValidationWrapper Component using something like v$.[keyField], but I'm unsure about the type to set for ...

Compiling TypeScript on save disrupts AngularJS functionality in Visual Studio 2017

I am currently working on a project in Visual Studio Community 2017 (15.2) that involves AngularJS 1.6.5 and a NancyFX server. You can find the code for this project here: https://github.com/GusBeare/NancyAngularTests This project serves as a learning pl ...

An object in typescript has the potential to be undefined

Just starting out with Typescript and hitting a snag. Can't seem to resolve this error and struggling to find the right solution useAudio.tsx import { useEffect, useRef } from 'react'; type Options = { volume: number; playbackRate: num ...