The type is lacking the following properties in array.push

Encountering an issue with the register page in my IONIC app.

Currently, I am utilizing a data.json file to store all user data, and I aim to create a new member with minimal information required (name, email, password) while leaving other fields empty for now.

The problem lies in the arrayPush method where certain properties are missing (the ones intended to be left blank).

This is the TypeScript code:

import {Component, Input, AfterViewInit, Output, OnInit} from '@angular/core';
import { async } from '@angular/core/testing';
import { Router } from '@angular/router';
import {AlertController, ModalController, NavParams} from '@ionic/angular';
import data from '../../../../data.json';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
  @Input() fullName = '';
  @Input() email = '';
  @Input() password = '';
  @Input() repeatPassword = '';

  messageString: string;
  today = new Date();

  constructor(private router: Router, private alertController: AlertController) {}

  ngOnInit() {}

  onRegister() {
    // Fetch HTML input data and validate. Show alert if invalid.
    if (this.fullName === '') {this.messageString = "You didn't enter a name.";this.errorMessage();return;}
    if (this.email === '') {this.messageString = "You didn't enter an email address.";this.errorMessage();return;}
    if (this.password === '') {this.messageString = "You didn't enter a password.";this.errorMessage();return;}
    if (this.password != this.repeatPassword) {this.messageString = "The passwords don't match.";this.errorMessage();return;}

    var firstname = this.fullName.split(" ")[0];
    var lastname = this.fullName.split(" ").pop();
    
    // Save data to JSON
    (data).members.push({ 
      fullname: this.fullName,
      firstname: firstname,
      lastname: lastname,
      mail: this.email,
      password: this.password,
    });
    
    // Redirect to homepage
    this.router.navigateByUrl('/home').then(r => {});
  }
  
  // Display error alert when emails do not match
  async errorMessage() {
    const alert = await this.alertController.create({
      cssClass: 'alerts',
      header: 'ERROR',
      message: this.messageString,
      buttons: [
        {
          text: 'Okay',
          cssClass: 'yes'
        }
      ]
    });
    await alert.present();
  }

}

This represents my data.json content:

{
  "members": [
    {
      "id": 1,
      "gender": "0",
      "fullname": "X X",
      "firstname": "X",
      "infix": "",
      "lastname": "X",
      "number": "06-12345678",
      "mail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cabfb9afb88aa9a5a7baaba4b3e4a9a5a7">[email protected]</a>",
      "image": "https://pbs.twimg.com/media/EHMN4bVWoAUXhUz.jpg",
      "password": "admin1",
      "birthdate": "14-07-2001",
      "country": "Netherlands",
      "address": "Testweg 1a",
      "state": "Noord Holland",
      "city": "Amsterdam",
      "zip": "1234BC",
      "subscription": "26 Dec. 2020"
    }
  ]
}

I intend to fill only these JSON objects for a new user: fullname, firstname, lastname, email, password

Answer №1

Foreword: I am unsure of the exact purpose behind the code, but the explanation provided below addresses the issue related to data types that you raised. However, the code snippet illustrated entails pushing to a data array obtained from `data.json`, without any storage mechanism evident in the code shown. As pointed out by JSON Derulo, adding elements to the array has no impact on the actual `data.json` file; it merely affects the in-memory array.


It appears that TypeScript is deducing the type of `data` based on `data.json`, given that you haven't defined a specific type. TypeScript does not have the capability to automatically recognize optional properties; explicit declaration is required for that purpose.

There are various approaches to address this issue:

  • Manually list all properties in a type definition.
  • List only the optional properties in a type definition, enabling inference for the remaining (required) properties.
  • Specify only the compulsory properties in a type definition, allowing inference for the other (optional) properties.

Among these options, the last one aligns best with your scenario:

import sampleData from "../../../../data.json";

type MemberType =
    Partial<typeof sampleData["members"][number]>
    & Pick<
        typeof sampleData["members"][number],
        "fullname" | "firstname" | "lastname" | "mail" | "password"
    >;

const data: typeof sampleData & {members: MemberType[]} = sampleData;

Playground link

This approach allows TypeScript to derive the type from `data.json`, set all properties as optional, and subsequently enforce original definitions for mandatory properties.

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

Encountering an Error in Angular Material 8 due to the Import of the Unforeseen Directive 'MatCard'

I keep encountering the error message displayed above in the console. I am currently working with Angular Material version 8.2.3. In my app.module.ts file, I have the following import statements related to Angular Material: import { MatInputModule, MatBu ...

Troubleshooting: JQGrid not displaying records in ASP.net application connected to MySQL database

Can someone please assist me with my issue? This is my third post, and I am having trouble displaying records from my MySQL database. Any help would be greatly appreciated. Thank you in advance. ItemCode.aspx <script type="text/javascript"> ...

Leveraging prop data to create dynamic router links in Vue

I am attempting to develop a feature that will dynamically update links on ion buttons depending on the props received. So far, I have: <template> <ion-button router-link :to "`$/+ {{subLink1}}" shape="round">{{linkName1}}& ...

PHP code to generate a JSON file with a multi-dimensional array: "

Within my web application, I am utilizing JSON. It is necessary for me to generate the following JSON file format using PHP. { "title": "A fantastic article", "clicks": 4000, "children": null, "published": true, "comments": [ ...

Conceal optional navigation bar options once a user has logged in - utilizing Angular 8

I need assistance with hiding certain links in my navbar once a user has logged in. Below are the current navbar menus: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav ...

Add an array to an existing array of objects

I am working with an array of objects displayed below. var myArray = [ { Data: '455', Note: 'tre', Id: '4' }, { Data: '456', Note: 'bre', Id: '5' }, { Data: '457', Note: 'cre&ap ...

The AJAX functionality seems to have broken following the switch from php5 to php7

When I initially wrote my code in php5, the index page would make an ajax call to check if $_SESSION['user'] was stored. If a session existed, the user's information would be displayed; otherwise, the page would redirect to the login page. H ...

Can I modify the cookie domain for NestJS SessionModule on a per-request basis?

I am currently using NestJS with SessionModule to handle user cookies successfully. However, I have a requirement to override the domain name for certain requests. I am uncertain about how to achieve this within NestJS, as the domain setting appears to b ...

Display a preview of a CSV file in a datagrid after uploading

My goal is to upload a csv file to the backend and show a preview of the data on the same page without refreshing or reloading. I believe using AJAX is the way to achieve this. I am curious about how we can accomplish this with Ajax and jQuery in the cont ...

Python: extract the decimal part of a floating-point number before the "e" exponent

Currently, I am utilizing Python for some mathematical calculations. At one point in the process, an array will be generated that appears like this: [1.23e-21, 2.32e-14, 8.87e-12, .....] My goal is to extract the values before the e.., meaning I want the ...

Converting a string containing a list of dictionaries into an actual list of dictionaries in Python

Looking for input on transforming a string into a list of dictionaries. This is the string I have: '{"screen_name":"Brian","avatar":1},{"screen_name":"David","avatar":21},{"screen_name&q ...

Tips for handling a JSON payload using Drop Wizard

I currently have a straightforward class named Thing public class Thing { private int id private String name //getters, setters, constructor } I am interested in sending a request with data and handling it. The request structure would be like this ...

Enhance your Spring application with a custom JSON deserializer using RestTemplate

When I receive a JSON response, it is structured like this: [ { "name": "This" }, { "name": "That" } ] Instead of creating a POJO to handle an array of POJOs, I prefer to simply retrieve the values as a String array. How can I direct Jack ...

What is the best way to add a clickable link/button in Angular 8 that opens a webpage in a new tab?

I'm looking to create a website that opens in a new tab when a link or button is clicked. I'm unsure how to achieve this in Angular 8. ...

Incorporating a visual progress indicator on the webpage

I am attempting to create a progress bar in Angular using the angular mat-stepper. Here is the code I have written so far: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { Ap ...

Obtaining child elements of the DOM within an Angular Component that has already been instantiated: A step-by-step guide

Imagine I have a component called <app-parent></app-parent>. The corresponding file is named parent.component.ts. Within app.component.ts, I create an instance of it with the following child element: <app-parent> <h1>Hello</h1& ...

The declaration file for 'autobind-decorator' is missing in TypeScript and cannot be located

Having a bit of trouble with my Typescript project. I'm trying to import the 'autobind-decorator' package, but I hit a roadblock. When compiling, I keep running into this error: cannot find declaration file for 'autobind-decorator&ap ...

Create JSON data from SQL Server

I'm looking to create a JSON string from a SQL table by using the FOR JSON AUTO qualifiers, where one or more columns store data in JSON format. For example: Table: Persons First_Name | Family_Name |City | Children --------------+-------- ...

Unable to send WhatsApp messages using Java

I'm seeking assistance to tackle this issue. My plan involves sending a WhatsApp message using Java with the help of a WhatsApp Gateway. Below is the Java code: import java.net.*; import java.io.BufferedReader; import java.io.OutputStream; import java ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...