"Encountered a problem when trying to access properties within a

Struggling to access properties of a nested object in TypeScript while using Angular, I encountered the following error: Object is possibly 'undefined'. Here is the code snippet:

export interface Address{
city?: string;
neighborhood?: string; 
}


export interface Programming{
backend?: string;
frontend?: string;
}

export interface NestedObject{
    firstName?: string;
    lastName?: string;
    completeAddress?: Array<Address>
    fullStackKnowledge?: Array<Programming>
}


this.example=[
      // First user 
      { 
        
        firstName: 'Msaddak',
        lastName: 'Rouabeh',
        
        
        completeAddress: [
          {
            city: 'Gafsa',
            neighborhood: 'Cité Hached Lalla',
          },
          {
            city: 'Monastir',
            neighborhood: 'Skanes',
          }
        ],
        fullStackKnowledge: [
          {
            backend: 'Express js',
            frontend: 'Angular',
          },
          {
            backend: 'Spring boot',
            frontend: 'React js',
          }
        ]
      },
      // Second user
      {
        firstName: 'Houssem',
        lastName: 'Ilahi',
        completeAddress: [
          {
            city: 'Tunis',
            neighborhood: 'Bardoo',
          },
          {
            city: 'Nabeul',
            neighborhood: 'Mrezka',
          }
        ],
        fullStackKnowledge: [
          {
            backend: '.net',
            frontend: 'Vue js',
          },
          {
            backend: 'Express js',
            frontend: 'React js',
          }
        ]
      }


    ]

This is how I attempted to access the data: Last name:

{{example[0].completeAddress[0].city}}</div>

However, I ran into this error: src/app/nested-objectt/nested-objectt.component.html:6:36 - error TS2532: Object is possibly 'undefined'.

Answer №1

Implement optional chaining

{{person?.[0]?.address?.[0]?.city}}

The ?. operator functions similarly to the . chaining operator, but instead of throwing an error when a reference is null or undefined, it simply returns undefined without continuing further. This is helpful when dealing with nested properties that may not exist yet.

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

Why don't my absolute paths work on nested folders in React and Typescript?

Struggling to configure absolute paths in my React project, encountering challenges with nested folders and the use of @ prefix. Here's what I have set up in my tsconfig.json: { "compilerOptions":{ "baseUrl":"src", ...

Is there a way to configure side={THREE.BackSide} using an external .glb file?

As a beginner in Threejs, I am trying to incorporate the use of side="THREE.BackSide" with an external model file named room.glb. My development environment consists of nextjs 13 (with typescript and app directory enabled) along with @react-three ...

The combination of arrays and array methods in intersection types may encounter difficulty in accessing all fields

I have two different types, both in the form of arrays of objects with specified fields, combined into an intersection type in Typescript. When I access an element from the array, I can retrieve the second field without any issues. However, when I try to ...

Tips for utilizing import alongside require in Javascript/Typescript

In my file named index.ts, I have the following code snippet: const start = () => {...} Now, in another file called app.ts, the code is as follows: const dotenv = require('dotenv'); dotenv.config(); const express = require('express' ...

Troubleshooting Access-Control-Allow-Origin Problem in Laravel API and Angular 5

I am currently working with Angular 5 on the front-end and Laravel 5.6 on the backend as a REST API. My current task involves obtaining an Access Token using the following code: const url = 'http://127.0.0.1:8000/oauth/token' ; const ...

``Error Message: TypeORM - could not establish database connection

I encountered an issue while running my project built with Typescript, Typeorm, and Express. The error message received when running the dev script was: connectionNotFoundError: Connection "default" was not found The content of my ormconfig.json ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

Steps to handle Angular's response to an HTTP 401 error

I am using nodejs (express) as a server side and angular 6 as the client. On the server, I have a middleware function that checks for a session. If the session is invalid or does not exist, I want to send a response to the client so it can handle it accord ...

Exploring the capabilities of the hardware camera in Angular 2

Struggling to implement the tutorial in Angular2. The challenge lies in making navigator.mediaDevices.getUserMedia function properly. The error message indicates that mediaDevices is not recognized on type 'navigator'. Refer to the media capture ...

Transferring information from a chosen <mat-option> to a different component in Angular Material

I am currently facing an issue with two components in my Angular application. The first component includes an Angular Material mat-option to select an option from a dropdown menu, while the second component is supposed to display the selected data. I attem ...

`Next.js: Addressing synchronization issues between useMemo and useState`

const initializeProjects = useMemo(() => { const data: ProjectDraft[] = t('whiteLabel.projects', {returnObjects: true}) const modifiedData: ProjectWL[] = data.map((item, index) => { return { ... ...

Error message displayed indicating script not found after executing yarn tsc within a Docker container

Using docker, I successfully built my project by running yarn tsc. However, when I executed docker run -p88:5011 accounts2 I encountered the following error: PM2 error: Error: Script not found: /home/accounts/dist/server/index.js. This error occurs despit ...

Vue defineProps allows for the definition of complex types for properties

Within my code, I am exploring the use of complex prop types in certain instances. Below is an example of what I have in mind: enum Country { [...] } interface IPerson { firstname: string; lastname: string; } interface IAddress { street: string; ...

*ngFor not functioning properly within Angular ionic modal

While working on my Ionic application with Angular, I encountered an issue with the ngForm not functioning properly inside a modal. I have tried to identify the problem with a simple code snippet: <li *ngFor="let item of [1,2,3,4,5]; let i = index ...

Angular Link Panel

I'm working on a marketplace app and I need to display a picture and name of a product when someone shares a link. Similar to how social media posts include a picture and title when shared. Can this be achieved using Angular, and if so, what steps do ...

The use of credentials is not allowed when the ‘Access-Control-Allow-Origin’ CORS header is set to ‘*’

My Java web application makes CORS requests where the browser performs an OPTIONS preflight before the actual request. The format of each request is as follows: Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/2 ...

Converting Typescript Object Types to Array Types with Tuple Structures

Presently, I have the following: interface Obj { foo: string, bar: number, baz: boolean } The desired outcome is to convert this interface into the tuple format below: [string, number, boolean] Is there a way to achieve this conversion? Up ...

What is the reason behind Rollup flagging code-splitting issues even though I am not implementing code-splitting?

In my rollup.config.js file, I have only one output entry defined as follows: export default { input: './src/Index.tsx', output: { dir: './myBundle/bundle', format: 'iife', sourcemap: true, }, plugins: [ ...

Describe the TypeScript type for an object with constant keys

My query resembles the one found in this Typescript interface definition question, but has a slight variation. I am beginning with an object where the keys are constants: const KEYS = { KEY1: 'hello', KEY2: 'world' } as const; How ...

Navigating through a node tree and making changes to its configuration and content

Here's the input I have. Some nodes have downlines with multiple other nodes nested inside. data = [ { "user_id": "1", "username": "johndoe001", "amount": "0.00", "down ...