Advanced Typescript Interface Incorporating Objects

I'm facing an issue with my address interface setup. Here is how it's defined:

export interface Address {
    addressType: {
        house?: {
            streetAddress: string,
            city: string,
            zip: string,
        },
        apartment?: {
            streetAddress: "",
            unitNumber: "",
            city: "",
            zip: "",
            buildingName?: "",
        },
    }
    instructions?: string;
}

In my Typescript component file, I have tried to define a house address like this:

address: Address;

constructor() {

    this.address.addressType = {
      house: {
        streetAddress: "1 test",
        city: "test city",
        zip: "92222",
      }
    }        
    console.log(this.address);
}

However, when I log the address to the console, I encounter the error message:

Uncaught (in promise): TypeError: Cannot set property 'addressType' of undefined

I believed I was setting the addressType correctly in the constructor. Is there a more effective way to achieve what I intend to do?

Answer №1

Prior to setting the addressType property for this.address, it is essential that you first initialize it:

constructor() {

    this.address = {
      addressType: {
        house: {
          streetAddress: "1 test",
          city: "test city",
          zip: "92222",
        }
      }
    };        
    console.log(this.address);
}

Answer №2

Start by setting up your address variable to point to an object. This will allocate memory for your object and allow you to set nested properties later.

address: Address = { addressType: {} };

constructor() {

    this.address.addressType = {
      house: {
        streetAddress: "123 Main St",
        city: "Anytown",
        zip: "54321",
      }
    }        
    console.log(this.address);
}

Answer №3

To avoid any issues with uninitialized properties, it is important to initialize the address property before use. When a property is annotated with a type but not given a value, its initial value is set to undefined.

You can initialize the property like this:

address: Address = { addressType: {} };

However, a better approach would be to create a class based on the Address Interface:

export interface IAddress {
  addressType: {
    house?: {
      streetAddress: string,
      city: string,
      zip: string,
    },
    apartment?: {
      streetAddress: "",
      unitNumber: "",
      city: "",
      zip: "",
      buildingName?: "",
    },
  }
  instructions?: string;
}

class Address implements IAddress {
  addressType: { house?: { streetAddress: string; city: string; zip: string; }; 
  apartment?: { streetAddress: ""; unitNumber: ""; city: ""; zip: ""; buildingName?: ""; }; };
  instructions?: string;
  constructor() {
    this.addressType = {}; 
  }
} 

You can then use it like this:

address: Address = new Address();

The house property of addressType is currently undefined

// This will throw an error because you are trying to access streetAddress of undefined
{{address.addressType.house.streetAddress}}

To solve the error above, make sure to initialize the house property just like the addressType:

  constructor() {
    this.addressType = {}; 
    this.addressType.house = {}
  }

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

How can Angular CLI add extra static resources while live reloading?

Currently, I am utilizing the most recent version of the Angular CLI. The issue I'm facing involves mock http calls that reference local JSON files such as '../app/myfile.json'. When I reload the application, I consistently encounter 404 err ...

Is there a way to update Checkbox changes within a Datagrid without selecting the entire row?

My Table Cell Checkbox Behavior Issue: Within a table cell, I have a checkbox that changes upon clicking it. However, the change only occurs the first time. Subsequent clicks on the same checkbox do not trigger any change until I click outside the cell. T ...

"Utilizing the power of union types within a generic function

Here is some code I am working with: /** Explains why there is no value */ export interface None { 'is none because': string; // Includes spaces to decrease the chance of confusion with a non-None member } /** Represents either a value ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

The cross-origin resource sharing configuration has not been implemented

I have SenseNet 7.0.0 and ASP.NET 5.2.3 set up, with my Angular (Typescript) application running on localhost:4200 and the ASP.NET application running on localhost:55064. I followed this tutorial for installing Sensenet and used this tutorial for installin ...

Angular 9 - Auto-adjust the height of the text box as the user types, returning to its original size when no longer in focus

I need a solution where an input field's height adjusts to display the user's entry, then returns to normal size when they click away. It should function similar to this example image: https://i.stack.imgur.com/yKcik.png Once the user enters th ...

Why should we include the '#' character in jhipster URLs?

Standard Angular applications typically do not include a '#' sign in their URLs. However, in JHipster URLs, the '#' character serves a specific purpose. Can you explain the significance of the '#' symbol in JHipster URLs and h ...

Angular 6's lazy loading feature causing a problem of not being able to match any routes

I'm currently working on implementing lazy loading in my Angular application. Below are the routes I've set up: app-routing.module.ts const routes: Routes = [ { path: '', loadChildren: './customer/customer.module#Custom ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

Using jest-dom without Jest is definitely an interesting challenge that many developers may

Can anyone help me with extending Typescript interfaces? I have come across a situation that I am trying to solve. In my tests, I am utilizing expect without using Jest directly (I installed it separately and it functions properly). Now, I am interested ...

The absence of 'SyncTestZoneSpec' error appeared while running karma test in angular 4

Let's start by addressing the current state of my project on the /develop branch, which is all in order with passing tests. To improve code readability, I decided to create a branch specifically for cleaning up the imports and implementing aliases in ...

Attempting to utilize pdf.js may result in an error specifying that pdf.getPage is not a recognized function

After installing pdfjs-dist, I attempted to extract all text from a specific PDF file using Node and pdfjs. Here is the code I used: import pdfjs from 'pdfjs-dist/build/pdf.js'; import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry.js&a ...

Is the Typescript index signature limited to only working with the `any` type?

I recently made changes to my interface and class structure: export interface State { arr : any[]; } export const INITIAL_STATE: State = { arr: [] }; This updated code compiles without any issues. Now, I decided to modify the Interface to incl ...

Troubleshooting a metadata issue while pre-compiling a feature module in Angular 2

Currently, I am in the process of developing an Angular2 library using Angular2 RC6. This particular library consists of a single module: import { Component, OnInit, NgModule } from '@angular/core'; import { CommonModule } from '@angular/c ...

Struggling to transmit data to material dialog in Angular2+

I am facing an issue with my Material Dialog not working properly. Can anyone point out what I might be missing? product-thumbnail.ts I will use this to trigger the dialog export class ProductThumbnailComponent implements OnInit { @Input() product: Pr ...

The art of binding styles and classes in code

What is the advantage of using style binding and class binding in Angular compared to directly using HTML style and traditional class attributes? <img src="link_img" [style.width]="imgWidth"> over <img src="link_img" width="200"> Looking fo ...

Navigating with Angular 7

Encountering an issue with my Angular 7 Application Here is the error message: Error: Invalid configuration of route 'dashboard'. One of the following must be provided: component, redirectTo, children or loadChildren In the process of develo ...

Retrieving data from a service and passing it between components in Angular 7

I have a variable called testgetinfos that holds an array of objects returned from a service. I need to access this variable in another component. Here is the function where I am retrieving the object array from a service. When I print the output of the t ...

Creating an Angular 2 service that relies on other services, while allowing components to inject only the parent service

In the scenario where a ParentService depends on ChildService, it is important to list both services in the "providers" attribute of the @Component definition. Is there a method to configure ParentService to automatically inject ChildService, simplifying ...