How come Typescript claims that X could potentially be undefined within useMemo, even though it has already been defined and cannot be undefined at this stage

I am facing an issue with the following code snippet:

  const productsWithAddonPrice = useMemo(() => {
    const addonsPrice = addonsSelected
      .map(id => {
        if (addons === undefined) { return 0}
        return addons.find(addon => addon.id === id).price})
      .reduce((a, b) => a + b, 0);
    return [...products].map(p => {
      const productCopy = { ...p };
      productCopy.price += addonsPrice;
      return productCopy;
    });
  }, [addonsSelected, products, addons]);

The code works fine in non-typescript environment and 'addons' is always initialized as an empty array, so it should never be undefined.

function useProductAndAddon(products: any[], addons: AddonType[] = []) {

But I'm getting a typescript error on this line:

return addons.find(addon => addon.id === id).price})

The error says:

Object is possibly 'undefined'.ts(2532)

This seems incorrect since I'm already checking for undefined on the line above it:

if (addons === undefined) { return 0}

This issue appears to be related to Typescript can't tell I'm returning early if param is undefined. However, I'm struggling to find a solution. Any clarification or guidance on this matter would be greatly appreciated.

Answer №1

If the addon with that specific id cannot be located, the result will be undefined

The find() function retrieves the value of the first element in the given array that meets the conditions specified by the testing function. If no elements meet the criteria, undefined is returned.

Refer to MDN

You can consider implementing something like this:

     .map(id => {
        const addon = addons?.find(a => a.id === id);
        return addon?.price ?? 0;
        })

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

Tips for verifying the response and status code in Angular 8 while uploading a file to an S3 Presigned URL and receiving a statusCode of 200

Looking to Upload a File: // Using the pre-signed URL to upload the file const httpOptions = { headers: new HttpHeaders({ 'Content-Disposition': 'attachment;filename=' + file.name + '', observe: 'response' }) }; ...

The RxJS observable fails to initiate the subscribe function following the mergeMap operation

I am attempting to organize my dataset in my Angular application using the RxJS operators and split it into multiple streams. However, I am facing difficulties making this work properly. Inside my SignalRService, I have set up a SignalR trigger in the cons ...

How can I generate pure JavaScript, without using Typescript modules?

Take this scenario as an example ... index.ts import { x } from "./other-funcs"; function y() { alert("test"); } x(y); other-funcs.ts import { z } from "some-module"; export function x(callback: () => void): void { z(); callback(); } ...

After calling sequelize.addModels, a Typescript simple application abruptly halts without providing any error messages

My experience with Typescript is relatively new, and I am completely unfamiliar with Sequelize. Currently, I have only made changes to the postgres config in the .config/config file to add the dev db configuration: export const config = { "dev" ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...

Style will be applied to Angular2 when the object's ID exceeds 100

I am working with object markers that have different Id's assigned to them. Now, I am trying to apply additional styling when the id > 100. Check out the code snippet below: <span *ngIf="result.object.reference > 100" class="tooltip-data"&g ...

Creating Typescript packages that allow users to import the dist folder by using the package name

I am currently working on a TypeScript package that includes declarations to be imported and utilized by users. However, I have encountered an issue where upon publishing the package, it cannot be imported using the standard @scope/package-name format. I ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Utilizing the await keyword within a forkJoin operation in TypeScript

I am facing an issue where I need to fetch a new result based on the old result. When a specific parameter in my primary call is X, it should trigger another function. However, the problem I'm encountering is that the scope of the program continues ru ...

Tips for showcasing saved images in Spring Boot with Angular 4

I am currently utilizing Spring Boot in combination with Angular 4. The issue I am facing involves uploading an image to the project location. However, upon attempting to view the uploaded image, it does not display correctly and instead throws an error. H ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

A Unique Identifier in Kotlin

In my typescript class, I have a member that accepts any as the name: interface ControlTagType { type?: String | null; [name: string]: any } class ControlTag { tagSource: String | null = null; tag: ControlTagType | null = null; } expor ...

The module 'module://graphql/language/parser.js' could not be resolved

I'm facing an issue while creating a React Native TypeScript project on Snack Expo. Even though I have added graphql to the package.json and included the types file, I keep getting this error : Device: (1:8434) Unable to resolve module 'module:/ ...

Determine the reference type being passed from a third-party component to a consumer-side component

I recently came across this issue with generics when using forwardRef in React: Property 'ref' does not exist on type 'IntrinsicAttributes' Let me explain my situation: import React from "react"; interface ThirdPartyComponen ...

The functionality of the disabled button is malfunctioning in the Angular 6 framework

Just starting out with angular 6 and I'm using formControl instead of FormGroup for business reasons. app.component.html <button class="col-sm-12" [disabled]="comittee_Member_Name.invalid && comittee_Member_Number.invalid && c ...

Guide on building a Vue3 component with TypeScript, Pug Template engine, and Composition API

Whenever I try to export components within <script setup lang="ts"> and then use them in <template lang="pug">, an error is thrown stating that the component is defined but never used. Here's an example: <template la ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

Exploring the benefits of integrating Apache Thrift with TypeScript

After running the apache thrift compiler, I now have generated .js and .d.ts files. How do I incorporate these files into my current Angular2/Typescript project? I attempted to do so with the following lines of code: ///<reference path="./thrift.d.ts"/ ...