The optional chaining feature seems to be malfunctioning as it is unable to access the property '0' of an undefined value

Why isn't optional chaining working in this scenario?

.html

 {{userItemModel?.item?.priceList[0]?.sellerUrl}}

An error is displayed:

TypeError: Cannot read property '0' of undefined

"@angular/core": "~10.1.1",

"typescript": "~4.0.2"

 "priceList": [
                {
                    "amount": 14.5,
                    "currency": "USD",
                    "sellerUrl": "https://www.bay.com/itm/Lear-6910-/33372049",
                    "basePrice": 15,
                    "discount": 10
                }
            ],

Update

Use case 1:

  Parser Error: Unexpected token [, expected identifier or keyword at column 33 
in [{{userItemModel?.item?.priceList?.[0]?.sellerUrl}}] in 

Use case 2:

Parser Error: Unexpected token [, expected identifier or keyword at column 33 in [

                    {{userItemModel?.item?.priceList?.[0].sellerUrl}}
                ] in 

Answer №1

To prevent errors when chaining array access, it is recommended to use arr?.[index]:

var example = {}
try{
  console.log(example?.sample[0])
}
catch(error){
  console.log(error.message)
}
console.log(example?.sample?.[0])

Note: Currently, there is a known issue with Angular related to this topic.

Answer №2

After attempting to replicate your scenario using Typescript Playground, I delved into the underlying mechanics to double-check for any typos on my end.

You can take a look at what I did here: TypeScript Playground

Here is an example of what I tested:

type PriceList = {
    amount: number;
    currency: string;
    sellerUrl: string;
    basePrice: number;
    discount: number;
}

type Item = {
    priceList?: PriceList[]
}
type UserItemModel = {
    item?: Item
}

const userItemModel: UserItemModel = {
    item: {
        priceList: [
            {
                amount: 14.5,
                currency: "USD",
                sellerUrl: "https://www.bay.com/itm/Lear-6910-/33372049",
                basePrice: 15,
                discount: 10
            }
        ]
    };
};
const firstPriceListSellerUrl = userItemModel?.item?.priceList?.[0]?.sellerUrl;

Based on this structure, everything appears to be functioning as expected without any issues.

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 is the process for redirecting to a Courier site using the consignment number of the item?

Currently, I am working on an e-commerce project that involves redirecting customers to a specific courier site where they can track their shipments using the consignment number. My goal is to make this process seamless for the user so they don't have ...

Encounter an error message stating "Request failed with status code 502 nginx in Next.js TypeScript."

After setting up Next.js typescript with Kubernetes NGINX Ingress, I encountered a problem where specific routes were returning a 502 error. For example, the route /test works fine, but /login does not. I'm unsure whether the issue lies with Kubernete ...

Sharing data from AJAX calls in Vue using vue-resource

After using Vue resource, I'm attempting to create an AJAX call that is based on the data received from a prior AJAX call. I have successfully bound the data fetched from /me to the userDetails prop. However, when trying to pass userDetails.id into t ...

Stopping the Bootstrap carousel when an input is focused

I have a Bootstrap carousel with a form inside. The carousel is set to pause when hovered over, but I noticed that if the cursor leaves the carousel while typing in the inputs, it goes back to its default cycle of 5000ms. I want the carousel to remain pau ...

Failed network request in my ReactJS project under the "Auth/network-request-failed" error code

I'm currently working on a project focused on learning to use react-router-dom and firebase authentication for user sign-in and sign-up. However, I've run into an issue where I keep getting a FirebaseError: "Firebase: Error (auth/network-request- ...

How does express.route determine the route?

I have recently started learning about Node.js (specifically with Express.js) and React.js. As a result, I have some questions regarding Express Router. Let me share a portion of my code with you: server.js const app = express(); const apiRouter = requi ...

Is the scope name not being properly isolated within the controller?

Currently exploring AngularJS and experimenting with $routeProvider, Here is what I have in my HTML: <div class="container"> <h1>AngularJS Practice</h1> <div ng-view> </div> </div> In my app.js file, I have the ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

How can I navigate to an external URL without Angular automatically adding "localhost:xxxx" to the address?

I am working on implementing a guard that will redirect users to an external service (such as Instagram) if they are not logged in. if (!loggedIn) { this.location.go(this.instagramLoginUri); } The URI for the Instagram login is: https://api.instagram ...

Trouble with Loading Bootstrap CSS File

Having some trouble with Bootstrap - I'm following a basic tutorial and everything seems to be working fine, except the CSS file isn't loading properly. I've checked on StackOverflow but couldn't find a solution that worked for me. Both ...

What is the best way to organize imports in an individual Angular component?

Is there a way to order the imports in a standalone component according to the same rules as the file imports? Let me explain. In my *.ts files, I use eslint rules to sort and group the imports at the top of the file. import/order": [ " ...

In Typescript, you can extend an interface with the Node type to specifically

I'm currently utilizing Cypress 10. I came across the following code snippet: Cypress.Commands.add( 'byTestId', // Taking the signature from cy.get <E extends Node = HTMLElement>( id: string, options?: Partial< ...

Using React Hooks to dynamically adjust onClick behavior based on history.location.path

I have a button that executes a function, but I want it to execute one of two functions based on the current URL (one button - two actions depending on location). Here is the current functionality of the button: const showApplyButton = () => { ret ...

What is the process for creating route transition animations in Angular RC.5?

Is there a new method for animating routes in transit since routeOnDeactivate has been removed? The official documentation on this topic seems to be unclear. ...

Having difficulties incorporating a selected custom repository into a module

Issue with Dependency Injection in NestJS Currently, I am working on implementing SOLID principles in my NestJS project by decoupling my service layer from TypeOrm. One of the benefits of this approach is the ability to switch between using an InMemoryRep ...

Provide solely the specified content range

While working with Node.js, my goal is to develop a video server that can serve a specific portion of a larger media file. Thanks to this gist, I have successfully created a video server and integrated it with an HTML5 video player using: <video contr ...

Insert a stylish border to frame the Google pie chart

I recently created a Google Pie chart and I'm looking to add a border around it. Can anyone provide assistance with this task? Below is the code for the Google Chart along with an image of how I would like it to appear. <!DOCTYPE html> ...

Ensure NodeJS/JSDom waits for complete rendering before performing scraping operations

I am currently facing an issue with scraping data from a website that requires login credentials. When I try to do this using JSDom/NodeJS, the results are inconsistent compared to using a web browser like Firefox. Specifically, I am unable to locate the l ...

Guide to executing various datasets as parameters for test cases in Cypress using Typescript

I am encountering an issue while trying to run a testcase with multiple data fixtures constructed using an object array in Cypress. The error message states: TS2345: Argument of type '(fixture: { name: string; sValue: string; eValue: string}) => vo ...

Customized pop-up alerts on web browsers

Is there a library available that provides notification features similar to those seen on Web Slack and Web Skype, allowing users to receive notifications even when they are not currently on the site page? https://i.sstatic.net/wANRg.png Thank you, and I ...