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

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

Handle and manage errors within the controller in Express.js to prevent the further execution of asynchronous functions

Consider a scenario where there is an API endpoint /register, designed to register new users in an application. The function utilized is asynchronous, as an attempt is made to incorporate an asynchronous process within an AuthController when performing pas ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

Incorporate the pdfmake.js file into my TypeScript file

Working on a VSTS web extension and looking to utilize PDFmake.js to generate a pdf. The PDFmake.js file needs to be imported into the node_nodules folder by running npm install pdfmake. To import this JavaScript file into my TypeScript file, I'm fol ...

A guide on passing an ngFor object variable to a function

I am trying to display subcategories for each category in my *ngFor list. The subcategory data is retrieved from Firebase using the category_id, but I am struggling to pass the category_id from the HTML to the function for every member of the category. ho ...

Can Vue instances support private computed properties?

Vue is a versatile tool that I utilize for both service classes and components. When it comes to reactive computeds, they prove to be incredibly beneficial. However, I often find myself wanting a clear way to differentiate between public interface compute ...

Unable to find the locally stored directory in the device's file system using Nativescript file-system

While working on creating an audio file, everything seems to be running smoothly as the recording indicator shows no errors. However, once the app generates the directory, I am unable to locate it in the local storage. The code I am using is: var audioFo ...

Using Typescript: Including an additional argument

While experimenting with the code provided in the documentation interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { x: number; y: number; constructor(x: number, y: num ...

The comparison of Booleans in Typescript sometimes produces inaccurate results

There is a strange issue I encountered in one of my classes involving a readonly boolean property. Whenever I try to check this property, the results are not as expected. Here is an example of the code: // vorgang is a reference to the class, isEK is the ...

Using Promise<void> instead of Promise<any> is the preferred approach

Working with AngularJS, I have created several asynchronous functions that all use the same signature, which is app.Domain.GenericModel.EntityBase (my generic model). Here is an example: get(resource: string): ng.IPromise<app.Domain.GenericModel.Entity ...

The ngAfterViewInit lifecycle hook does not get triggered when placed within ng-content

The ngAfterViewInit lifecycle hook isn't triggered for a Component that is transcluded into another component using <ng-content>, as shown below: <app-container [showContent]="showContentContainer"> <app-input></app-input> ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

The attribute 'body' cannot be found in the specified 'Request' type

Why does the req variable of type Request not show intellisense for the property body? Could this be related to typings? import { Request, Response } from 'express' import { ok, bad } from './responses' export const signIn: async (req ...

What could be causing the Intellisense errors in Visual Studio 2015 that say "Cannot find module 'angular2/core'"?

Currently, I am utilizing Visual Studio 2015 Update 1 in conjunction with TypeScript 1.8.5. Within my ASP.NET MVC 4.6 Web Application, Angular2 is being used. The TypeScript compile options have been configured with the following settings: <PropertyG ...

"Troubleshooting Typecscript and Angular: Dealing with mismatched argument

How can I resolve this Angular error: (response: HttpResponse<User>) => { which results in the following error message: Argument of type '(response: HttpResponse<User>) => void' is not assignable to parameter of type '(val ...

Restrict the discriminator value in a discriminated union from any other string literal union type in TypeScript

My discriminated union is quite basic, but I want to restrict the discriminator to only allow specific values that come from another string literal union type. This would simplify the process of adding new "cases" to the discriminated union. Here is a str ...

Issues with TypeScript Optional Parameters functionality

I am struggling with a situation involving the SampleData class and its default property prop2. class SampleData { prop1: string; prop2: {} = {}; } export default SampleData; Every time I attempt to create a new instance of SampleData without sp ...

Is there a way I can replace this for loop with the array.some function?

I am looking to update the filterOutEmails function in the following class to use array.some instead of the current code. export class UsertableComponent { dataSource: MatTableDataSource<TrialUser> createTableFromServer = (data: TrialUsers[], ...