Best practices for declaring props with custom types in Nuxt 3 using TypeScript to handle possible undefined values

Exploring the use of TypeScript in a Nuxt3 project for the first time has been quite an experience.

One specific component in the project is focused on either creating or editing a person in the backend:

<template>
  <UCard>
    <template #header>
      <h3 class="font-semibold text-xl">
        {{
          props.mode === "create"
            ? "Ajouter une personne"
            : "Modifier une personne"
        }}
      </h3>
    </template>

    <UForm :schema="schema" :state="state" class="space-y-2" @submit="onSubmit">

      <UFormGroup class="" label="Prénom" name="firstName">
        <UInput v-model="state.firstName" :disabled="props.mode === 'update'" />
      </UFormGroup>

      <UFormGroup class="" label="Nom" name="lastName">
        <UInput v-model="state.lastName" :disabled="props.mode === 'update'" />
      </UFormGroup>

      <UFormGroup class="" label="Email" name="email">
        <UInput v-model="state.email" />
      </UFormGroup>

      <UFormGroup class="" label="Téléphone" name="phone">
        <UInput v-model="state.phone" />
      </UFormGroup>

      // More form fields here...

    </UForm>
    <template #footer> </template>
  </UCard>
</template>

<script setup lang="ts">
// TypeScript logic here...

const props = defineProps({
  mode: String,
  person: { type: Object as () => IPerson },
});

// More TypeScript logic...

if (props.mode === "update") {
  state.id = props.person.id;
  state.firstName = props.person.firstName;
  state.lastName = props.person.lastName;
  state.email = props.person.email;
  state.phone = props.person.phone;
  state.memberSince = props.person.memberSince.substring(0, 10);
  state.memberLastYear = props.person.memberLastYear;
}

async function onSubmit(event: FormSubmitEvent<any>) {
  // onSubmit function logic...
}
</script>

Here's the structure of the IPerson interface:

export interface IPerson {
    // IPerson interface properties...
  };

Before integrating the

  typescript: {
    typeCheck: true
  }

into the nuxt.config.ts, everything ran smoothly.

However, upon adding the typeCheck: true, compilation yielded 9 errors, all revolving around the same issue:

ERROR(vue-tsc) 'props.person' is possibly 'undefined'.

Most of these errors stem from sections where props.person is used, particularly in this block of code:

if (props.mode === "update") {
  state.id = props.person.id;
  state.firstName = props.person.firstName;
  state.lastName = props.person.lastName;
  state.email = props.person.email;
  state.phone = props.person.phone;
  state.memberSince = props.person.memberSince.substring(0, 10);
  state.memberLastYear = props.person.memberLastYear;
}

After hours of searching online for a solution to this persistent issue, assistance is greatly needed.

Answer №1

After implementing this default value, the issue was successfully resolved

const properties = defineProperties({ theme: String,
    user: { type: Object as () => IUser, 
    default:  {id:null,firstName:'',lastName:'',email:'',phone:'',registeredSince:'',lastActive:''} }, });

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

What purpose does a cast serve when used on a return type that is defined generically?

Consider this straightforward property access function export function accessProperty<T, K extends keyof T, P extends T[K]>(name: K, v: T): P { return v[name] as P } What is the significance of the cast as P in this context? I experimented with ...

Step-by-step guide on incorporating a climate clock widget into your Angular project

Is there a way to integrate the Climate Clock widget from into my Angular project? Upon adding the following code snippet: <script src="https://climateclock.world/widget-v2.js" async></script> <script src="https://climateclo ...

The best location for storing Typescript files within an ASP.NET Core project

My Typescript app is built on AngularJS 2 with ASP.NET Core, and currently I store my TS files in the wwwroot directory. While this setup works well during development, I am concerned about how it will function in production. I aim to deploy only minified ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

Error message stating 'is not recognized' caused by Angular SharedModule

I have a navbar component that I've organized into a module called 'NavbarModule' so that it can be easily shared. My goal is to use this component in the 'ProductsListComponent'. However, even after properly importing and exportin ...

Ways to pass a class list from a client to a webmethod using AJAX

I have a list of client-side classes in TypeScript that I need to send to a web method. Here is my TypeScript code: class MakeReportData { LocalName: string; FldSi: number; ViewSi:number; TypeName:string ; CheckBoxshow :boolean ; ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

Prisma auto-generating types that were not declared in my code

When working with a many-to-many relationship between Post and Upload in Prisma, I encountered an issue where Prisma was assigning the type 'never' to upload.posts. This prevented me from querying the relationship I needed. It seems unclear why P ...

How to link observables in HTTP requests using Angular 5?

I'm currently developing an application using Angular 5, and I want to segregate raw http calls into their own services so that other services can modify the responses as needed. This involves having a component, component service, and component data ...

Is it possible to generate a property for an interface by casting a key within a for-in loop?

When I attempt to set a property on an object with a value from a dynamically generated form, I utilize a for-in loop to identify a property in the object and assign it. FormFeatureArray.forEach((el) => { // form handling stuff omitted For(c ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Utilizing Prisma Enum with Nest JS: A Comprehensive Guide

While working on my backend with Prisma and NestJS, I have encountered an issue. I defined an enum in Prisma that works fine in debug mode, but when I generate the Prisma client using nest build, I get an error. Object.values(client_1.RoomSharingType).join ...

What is the process for sending an email using Angular 6 and ASP.NET CORE web api?

When a user inputs their email and password in the designated boxes, they also include a recipient email address with a CC. This information is then sent via a web api. The email will contain text like "Total Sales Today" along with an attached PDF file. ...

What strategies can I use to preserve type narrowing when utilizing the Array.find method?

Within the code snippet below, I am encountering a typescript compilation error specifically in the Array.find method. Despite checking that `context.params.id` is not `undefined`, my type seems to lose its narrowing. I'm puzzled as to why this type ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

What is the best approach to testing the React Hook "useEffect" that is used to make an API call with Typescript?

Currently, I am working on writing Jest-enzyme tests for a basic React application using Typescript along with the new React hooks. The main issue I am facing is with properly simulating the api call made within the useEffect hook. Within the useEffect, ...

Filtering FieldSelector options in react-querybuilder: A step-by-step guide

I am currently working on a task to eliminate the fields from FieldSelector that have already been utilized. In my custom FieldSelector component, let's assume there are fields A, B, C, D, E available. If A & B have been used, they should not be ...

Explain the concept of utilizing curried state handlers within a React and Typescript application

I am currently working on defining the function that will handle change events to update the state value accordingly. This is what I envision the implementation to look like: handleChange: ChangeHandler<State> = field => value => this.set ...

Retrieving a value in the app component from a map using Angular

I have been struggling to display the values of ValueM, ValueR, and product in my app.component.html file. Can anyone offer a solution or tip to help me move forward? Thank you very much. app.component.ts forkJoin( this.service1.method1(filter1), ...