In Vue3, using the script setup feature allows for setting default property values within nested objects

I am developing a component that is designed to accept an object as a prop.

In case the object is not provided, I aim to set a default value for it.

<script setup lang="ts">
interface LocaleText {
  text: string;
  single?: boolean;
  count?: number;
  params?: any;
}
interface Title {
  title?: LocaleText;
}
interface Filter extends Title {
  items?: string[];
}
interface Props extends Title {
  filters?: Filter[];
}
interface Data {
  selectedStatus: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: (): LocaleText => ({ text: "ExampleText" }),
  filters: () => [] as Filter[],
});

function getText(text?: LocaleText): string | undefined | null {
  return text?.text ?? "null";
}
</script>
<template>
  <div>
    Example:
    {{ getText(props.title) }}
  </div>
</template>

The current output on the page is "Example:null"

I am struggling to pinpoint the reason behind this issue.

Answer №1

Based on the information provided in this official documentation excerpt:

It is currently necessary for the type declaration argument to be one of the following options in order to ensure accurate static analysis:

  • A type literal
  • A reference to an interface or a type literal within the same file

Therefore, the props should consist of a simple interface without extension:

<script setup lang="ts">
interface LocaleText {
  text: string;
  single?: boolean;
  count?: number;
  params?: any;
}
interface Title {
  title?: LocaleText;
}
interface Filter extends Title {
  items?: string[];
}
interface Props  {
  title:string;
  single?: boolean;
  count?: number;
  params?: any;
  filters?: Filter[];
}
interface Data {
  selectedStatus: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: LocaleText => ({ text: "ExampleText" }),
  filters: () => [] as Filter[],
});

function getText(text?: LocaleText): string | undefined | null {
  return text?.text ?? "nullVal";
}
</script>
<template>
  <div>
    Example:
   {{ getText(props.title) }}
  </div>
</template>

https://sfc.vuejs.org/#eNqlUz1v2zAQ/StXLpYAR9pV2UbRtOjQoUCDdggz0NLJYUCRBEklKVT99x4pxVHcMQtx9+7jvTuSI/tkbfE4IKtY7RsnbQCPYbB7rmVvjQswgsMOJuic6WFDqZtz6LPp7YIXZXRiJwo3RvsAvT/BLhZnm2+olIHfxqn2wybnui5nLmIhJ2BvlQhIHtSpZ0lmXZ5xtmUz41UvbPHgjSa5I2UDXwKeswoSEjFSEX3O7kOwvipL3zVR2oMvjDuVZBVu0EH2WKDvr47OPHl01Jiz2GLieiLKl4EuVwNK6NOOs0ga16QDuk40CN9NIxTe4DMtLfYJZFXgg5P69DECngyFhwqOxigUOoGNISmE6aE/okuQFU70njCh/xBAel5JbmRQuPSPJmW98l4mf5WKTKAI6tavayUtNzLM6m7...

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

Importing dynamic components on-the-fly in Vue version 2.7

Let me start by clarifying that I am currently working within a Vue 2.7 codebase powered by webpack. This means that any solutions related to Vue 3 or Vite will not be applicable in my case. I am in the process of revamping an old navbar that is generated ...

"Enhancing user input with a blend of material design and bootstrap-

I'm currently developing a Vue web application and utilizing bootstrap-4 as my CSS framework. I'm aiming to achieve input fields that resemble material design. However, Bootstrap offers only the older style of input fields with borders on all sid ...

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...

What is the best way to exhibit information from a lone table column in a modal using Angular 7?

Is there a way to have an "edit" button beside each row in the appointments table that triggers a modal popup allowing users to change appointment dates? Unfortunately, I'm facing an issue where the modal does not pop up and my screen turns white. ** ...

Guide on Implementing jQuery Plugin with Vue, Webpack, and Typescript

I am currently exploring the integration of the jQuery Plugin Chosen into my vue.js/Webpack project with TypeScript. After some research, I discovered that it is recommended to encapsulate the plugin within a custom Vue component. To kick things off, I m ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

When bootstrap buttons are displayed inside a Vue component, there should be no spacing between them

Is this issue specific to the vue-loader or is it more related to webpack builds in general? Consider a basic HTML page with Bootstrap 4 loaded and two buttons added: <button type="button" class="btn btn-primary">Primary</button> <button t ...

Obtaining context from a higher order component in the constructor of a child component: tips and tricks

In order to gain access to context throughout the application, I've implemented the following context provider: import React, { Component, useContext } from 'react'; import { appInitialization, Context } from "@microsoft/teams-js"; ...

Steps for enabling a function to return an undefined type

After extensive review, I have discovered that TypeScript has numerous hidden nuances, which make it less strict and accurate. I prefer to utilize 'undefined' as the return type for functions because it accurately reflects the reality of the sit ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

How can I verify the value of a class variable in TypeScript by using a method?

I need a more concise method to inform TypeScript that my client has been initialized (no longer null). While I have achieved this functionality, the current implementation seems unnecessarily verbose. Here is how it currently looks: export abstract class ...

Error: Module 'redux/todo/actions' could not be located. Please check the file path

Despite reading numerous posts and articles on getting absolute imports to work in a TypeScript project, I have not encountered any issues with this. My project is functioning properly with absolute imports. However, within VS Code, all absolute imports a ...

Learn how to easily close a Materialize CSS modal using Vue

My current challenge involves trying to close a Modal from Materialize CSS upon successful validation, but I am encountering an issue locating the form. The initial solution I tried was using type validation: v-if = "showModal," which worked to some exten ...

Exploring potential arrays within a JSON file using TypeScript

Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on. The structure of my JSON data is as follows: { "forename": "Maria", ...

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...

Display JSX using the material-ui Button component when it is clicked

When I click on a material-ui button, I'm attempting to render JSX. Despite logging to the console when clicking, none of the JSX is being displayed. interface TileProps { address?: string; } const renderDisplayer = (address: string) => { ...

The spread operator in Vuex is causing compilation errors with babel, as it continuously results in a module build failure

Currently, I am utilizing a spread operator within my mapGetters object. It is crucial to use a specific babel-preset-stage for proper ES6 compilation. Even after installing babel-preset-stage-2 via npm, I encountered the following error: ERROR in ./~/bab ...

How can one dynamically update a page in Angular when the path is changed?

I am facing a pagination issue in Angular. Here is my HTML code: <!-- A div element for pagination part at the bottom of the page --> <div style="margin-left: 50%; margin-top: 20px; margin-bottom: 20px"> <ul class="paginat ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...