Determine whether a nullable string property contains a specific string using indexOf or includes may result in an expression error

I am facing a challenge where I need to assign a value conditionally to a const. The task involves checking if a nullable string property in an object contains another nullable string property. Depending on the result of this check, I will then assign the const a value from either functionA or functionB. I have attempted to use both 'indexOf' and 'includes', but I keep encountering errors in TypeScript such as 'Object is possibly undefined' or 'expression expected'. If you have any suggestions on how to approach this problem by properly handling the nullability of the object and its properties while evaluating the condition, please share your insights. Any help would be greatly appreciated!

When using indexOf method, TypeScript shows an error indicating that Object might be 'undefined'

const value = (req.object?.propertyA?.indexOf(req.object?.propertyB?) >= 0) ? 
    functionA(req.object?.propertyA?) :
    functionB(req.object?.propertyB?)

On attempting to use includes method to search for the substring, TypeScript throws an error asking for an expression

const value = req.object?.propertyA?.includes(req.object?.propertyB?) ? 
   functionA(req.object?.propertyA?) :
   functionB(req.object?.propertyB?)

Answer №1

The issue stems from the usage of req.object?.propertyB.

Both String.prototype.indexOf() and String.prototype.includes() require a string parameter, but your code could potentially return undefined.

The use of ? suffix in this context is also inappropriate.

To improve clarity, I suggest modifying your code to first check for the existence of propertyB...

const value =
  req.object?.propertyB && req.object?.propertyA?.includes(req.object.propertyB)
    ? functionA(req.object?.propertyA)
    : functionB(req.object?.propertyB);

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

Angular 8 Observable: Managing User Objects

I recently developed a new service and attempted to call an API method (HTTP GET) to retrieve data, but I'm encountering an issue where not all the data objects from the API GET request are being displayed. angular-component.ts public allUsers$: Obs ...

Tips for achieving seamless map rotation in Mapbox

I need assistance with slowly rotating a map to a specific angle in Mapbox-gl js. I have tried two options for rotating the map, but I am struggling to achieve a slow rotation. 1. map.rotateTo() When I use map.rotateTo(angle,{duration: 2000}), I encounte ...

ESLint refuses to be turned off for a particular file

I am in the process of creating a Notes.ts file specifically for TypeScript notes. I require syntax highlighting but do not want to use eslint. How can I prevent eslint from running on my notes file? Directory Structure root/.eslintignore root/NestJS.ts r ...

Utilizing the dojo.xhrget() Method to Showcase Information in the Dojogrid

Trying to showcase a dataset retrieved asynchronously from the server using the dojo.xhrget() method. The intention is to update the grid with new values each time a user interacts with the content pane, without refreshing the entire page. However, running ...

Looking to prevent printing and saving a webpage directly from the file menu using JQUERY or JavaScript

I am in need of assistance to find a code that can disable the ability to print and save a webpage using JQUERY or JAVASCRIPT ...

Discover the versions of key libraries/modules within the webpack bundle

Is it possible to identify all the libraries, scripts, or modules included in a webpack bundle through the developer's console of a website that is already running, without access to its codebase? Additionally, is there a way to determine the version ...

Type inference in Typescript is especially powerful when used in conjunction with decorators

I am curious as to why the compiler in Typescript cannot infer the new type of a class when decorators or annotations are used. Interestingly, if I use the traditional ES5 method (manually calling the decorator), it works without any issues. Here is an ex ...

What is the process for constructing a regular expression (regex) in JavaScript to validate an id?

My validation requirements are relatively straightforward, but as someone who is new to regex, I am in need of quick assistance. The format should be either 1234567890 or 123456-7890, allowing for any number ranging from 0 to 9 and a total character length ...

What is the best way to execute an inline function two times in a row

I'm currently utilizing Gametime.js to create a real-time world chat feature. All messages are kept in a database for storage. Interestingly, PubNub, which is used by Gametime.js, seems to require messages to be sent twice for them to actually go th ...

Sharing an Angular scope variable with JavaScript

I have a streetName variable within an Angular scope. <script type="text/javascript"> angular.module('addApp').controller('add', ['$scope',function($scope) { $scope.streetName = "Bonita Ln"; }]); < ...

Address Book on Rails

Hello, I'm relatively new to this and would be grateful for any assistance. My goal is to utilize the data saved by a user in their address book, and then offer them the option to use that address for delivery. Below is my Address controller: class A ...

Hold on, the document will be available momentarily

There is a backend process that creates a file (which may take up to 1 minute). I created a function to check if the file is ready. function checkForFile() { $.ajax({ url: '/check/', // check if file exists success: function(data) { ...

How can I align Javascript output vertically in the middle?

I am currently facing an issue with a JavaScript clock displaying in a narrow frame: <!DOCTYPE html> <HTML> <HEAD> <TITLE>Untitled</TITLE> <SCRIPT> function checkTime(i) { if (i < 10) { ...

Loop through the array only if the property exists to avoid encountering the 'cannot iterate over undefined' error

Here's a code snippet that I'd like to simplify: if (this.props.fk_data) { if (this.props.fk_data.length > 0) { for (let fk_dataset of this.props.fk_data) { } } } I'm considering putting this.props.fk_data into st ...

Encountering the error message "index.d.ts is not a module" when using TypeScript typings

When I try to use the code below, I encounter the error File node_modules/@types/webrtc/index.d.ts is not a module: import * as webrtc from "webrtc"; const peerConnection1 = new RTCPeerConnection(); I have installed the typings using npm i @types/webrtc ...

Query about converting PHP strings to integers

Just a quick inquiry: I currently have strings that are formatted as '121', '9998', etc. These strings consist of numbers surrounded by single quotes. Could you please advise on how I can eliminate these quotes and convert the strings ...

Leveraging entities within entities with connections and seeding data in Nest JS / TypeORM

Imagine we are developing our initial entities for a brand new web application. We start with an entity for users: @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() username: string; @Column() password: string; ...

Add various inputs to a table using JavaScript

I came across a situation where I needed to append lines into a table in a specific way. However, I encountered an issue with JavaScript not accepting any input type='text' for an unknown reason. When I used a normal text variable, it worked fine ...

Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert ...

Overriding the Ajax URL

During an AJAX request in a Rails app triggered by onchange event, I am encountering an issue with the URL being called. The function for the request is a simple PUT operation: function quantityChange(id, val) { $.ajax({ url: 'cart_items/ ...