Exploring nullish coalescing with undefined values

My function is set up to make API calls:

interface getEventsPropsShape {
    eventId?: string;
    accountId?: string;
    eventsStartAfter?: string;
  }

  const getEvents = async ({
    eventId,
    accountId,
    eventsStartAfter,
  }: getEventsPropsShape): Promise<void> => {
    let apiUrl: string = '/v1/developer/events?limit=25&ascending=false';
    eventId !== undefined ?? (apiUrl += `&eventId=${eventId}`);
    accountId !== undefined ?? (apiUrl += `&accountId=${accountId}`);
    eventsStartAfter !== undefined ??
      (apiUrl += `&eventsStartAfter=${eventsStartAfter}`);
    const response = await get(apiUrl);

The approach works successfully as it doesn't include eventId in the apiUrl

let apiUrl: string = '/v1/developer/events?limit=25&ascending=false';
eventId !== undefined ?? (apiUrl += `&eventId=${eventId}`);

However, the following method does not produce the desired result because it adds eventId = undefined to the apiUrl

let apiUrl: string = '/v1/developer/events?limit=25&ascending=false';
eventId ?? (apiUrl += `&eventId=${eventId}`);

In essence, I am aiming to eliminate the need for conditional if statements like those seen here:

    if (eventId) apiUrl += `&eventId=${eventId}`;
    if (accountId) apiUrl += `&accountId=${accountId}`;
    if (eventsStartAfter) apiUrl += `&eventsStartAfter=${eventsStartAfter}`;

Answer №1

Replace ?? with &&. For instance:

let eventId = undefined;
let apiUrl = '/v1/developer/events?limit=25&ascending=false';

eventId && (apiUrl += `&eventId=${eventId}`);
console.log(apiUrl);

eventId = 'foo';
apiUrl = '/v1/developer/events?limit=25&ascending=false';
eventId && (apiUrl += `&eventId=${eventId}`);
console.log(apiUrl);

Alternatively:

let eventId = null;
let apiUrl = '/v1/developer/events?limit=25&ascending=false';

eventId !== undefined && (apiUrl += `&eventId=${eventId}`);
console.log(apiUrl);

eventId = 'foo';
apiUrl = '/v1/developer/events?limit=25&ascending=false';
eventId !== undefined && (apiUrl += `&eventId=${eventId}`);
console.log(apiUrl);

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

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

Leverage Async Await for Setting Response Data in TypeScript

Currently, I am making multiple API requests with different data and storing all the responses in an array. Then, I am using .map to map the response array to my original array to update the data. However, it seems like the process is not working correctly ...

Capturing user input with Angular Material forms in HTML

In the process of working on a project in Angular, I am utilizing the Angular Material component library. As part of this project, I am creating a form with multiple fields. Everything is functioning properly, however, the layout appears slightly off: ht ...

Deployment of a NextJS14 app to Vercel encountered an issue: Unexpected token '<' found in JSON at position 0

Here is the issue at hand: next: 14.1.4 next-auth: 4.24.7 node version: 20 This is the structure of my authentication folder: No errors occur when running npm run dev I've been investigating this issue for three days, but I am still stuck. I belie ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Adding an additional element to an object - crossroads of combining types versus sequential examination

Here's a query for you: AppendToObject. When I first tackled this question, my initial instinct was to utilize type intersection like so: type AppendToObject<T, U extends PropertyKey, V> = T & {[P in U]: V} Unfortunately, this solution did ...

Exploring the differences between Angular's @Input and @Output directives and utilizing Injectable Services

When considering the differences between @Input/@Output in parent and child components versus using services that are instantiated only once with dependency injection (@Injectable()), I find myself questioning whether there are any distinctions beyond the ...

Unusual behavior when importing in Angular 2 using TypeScript

While working on a demo for another question on Stack Overflow, I initially used angular-cli and then switched to Plunker. I noticed a peculiar difference in behavior with the import statement between the two setups. The issue arises with the second impo ...

The property 'toLowerCase' cannot be accessed as it is undefined or null

Scenario: A textbox is present with a list of data below it. Upon typing in the textbox, the list gets filtered based on the text entered. Code: Pipe: @Pipe({ name: 'search' }) export class SearchPipe implements PipeTransform { transform( ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

"Utilizing aws-sdk in a TSX file within a React project: a step-by

When working on a project using TypeScript (tsx) for React, I encountered an issue with uploading images to the server using aws-sdk to communicate with Amazon S3. To resolve this, I made sure to install aws-sdk via npm and typings. UploadFile.tsx import ...

The parameter of type 'never' cannot be assigned with the argument of type 'number | boolean | undefined'

In my project, I am creating a validation input using TypeScript in Next.js. interface InputRules { required?: boolean min?: number max?: number minLength?: number maxLength?: number } I have defined an object that contains methods to handle val ...

Verifying TypeScript errors before each commit in a Vue application

We have set up a git hook in our app using Husky for pre-commit actions. Whenever someone commits code, it triggers the pre-commit code - #!/bin/sh . "$(dirname "$0")/_/husky.sh" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_ ...

Securing Your Next.js Web App with Session Authentication

I have encountered a challenge while integrating NextAuth authentication into my React.js web application. To ensure seamless user authentication across the entire app, I am attempting to wrap a SessionProvider around the root component. However, VSCode ...

Using .on('mouseover', d => ..) does not yield the same `d` value as using .attr('foo', d => ..) in D3.js

I'm facing an issue with a mouseover tooltip in Observable that seems to fail when I transfer it to a Grafana plugin using React, D3, and Typescript. The technique I followed can be found in this article: Link to Article To simplify the code and deb ...

Configuring Stylelint in a NextJS project using Emotionjs

I recently encountered an issue while trying to integrate Stylelint into a new NextJS Typescript project with EmotionJS. Many rules were not working in my styles files, and the only error I could identify was Unknown word CssSyntaxError. This particular U ...

Having difficulty understanding Symbol.iterator and the return value type in a for-of loop while using TypeScript

Currently, I am delving into type script and embarking on a journey to learn how to craft generic containers for educational purposes. I have developed a LinkedList class with the intention of incorporating the ability to iterate over it, like so: for (co ...

Angular 4 file upload verification: Ensuring safe and secure uploads

Is there a recommended method to validate the file type when uploading a file in an Angular 4 form? Are there any simple ways to accomplish this task? ...

The dimensions of my Angular app have begun to unexpectedly expand

Currently in the process of developing an Angular application, I've encountered a frustrating issue. Each time I refresh the app using ng serve, the loading time seems to increase gradually. It can now take up to 10 seconds for changes to reflect in t ...

Implement a class in Typescript that allows for the addition of properties at runtime

I'm currently in the process of incorporating Typescript definitions into an existing codebase that utilizes the Knockout library. Within the code, there is a prevalent pattern that appears as follows: interface SomeProperties { // Assorted prope ...