Conditional logic in TypeScript can be applied to a Promise<boolean>, enabling the execution of code synchronously

In my business logic library, there is a method designed to run asynchronously that takes false as an argument in an if statement. When executed asynchronously, everything works fine:

const permissions = new PermissionProvider(userId, appId);

if(await permissions.ifAllowed('invalid action', itemID)){
     // This code will not be reached.
}

export class PermissionProvider {
...
public async ifAllowed(action: string, itemId?: string): Promise<boolean> {
    return await db.query(params)
    .then(() => { return false; }
}

However, I am worried that someone might unintentionally execute the code synchronously:

if(permissions.ifAllowed('invalid action', itemID)){
     // This code runs because asynchronous functions return a Promise,
     // and objects evaluate to true.
}

Simply relying on documentation instructing the API to be used with async/await seems risky. It could lead to unexpected consequences since it may not be immediately apparent to the end user that omitting the await keyword gives them virtually unrestricted access.

If I were to return a primitive boolean instead, the async code would then return undefined since it originates from the database as a Promise.

Is there a satisfactory solution to either enforcing asynchronous calls by the API consumer or preventing the if statement from evaluating to true?

I attempted to throw an uncaught error, but it still executes the code because the error is thrown after the if statement has already been evaluated.

Answer №1

Looking for a solution to either require async calls on the API consumer, or prevent the if statement from returning true?

You have the option of activating strict boolean expressions in your tslint configuration:

Answer №2

When needing to utilize external I/O, like in this particular scenario, achieving complete synchronicity is not possible. Furthermore, enforcing the use of await is impossible as omitting it remains valid code. However, this should not pose an issue, even for novice node.js/JS developers, as asynchronous code is prevalent. Simply ensure thorough documentation of your API and everything should run smoothly.

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

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

react-i18next: issues with translating strings

I encountered a frustrating issue with the react-i18next library. Despite my efforts, I was unable to successfully translate the strings in my application. The relevant code looked like this: App.tsx: import i18n from 'i18next'; import { initR ...

Assigning function types to functions that accept generics: A guide

type FormValidationHandler<FormValues> = (params: { formValues: FormValues, debugName?: string, }) => { isValid: boolean, fieldErrors: Record<string, unknown>, formError: string, } const validateForm: FormValidationHandler = param ...

There was an error during compilation: Module not detected - Unable to locate './xxxx'

Looking for help with importing a file from another folder into my Next.js project. I need assistance with the correct syntax and paths as I am encountering an error. Here is a link to the screenshot of the error: https://i.sstatic.net/jZ6kk.png Below are ...

How to convert typescript path aliases into relative paths for NPM deployment?

I am currently working on a typescript project that utilizes paths for imports. For instance: "paths": { "@example/*": ["./src/*"], } This allows the project to import files directly using statements like: import { foo } from "@example/boo/foo"; Whe ...

Erase Typescript Service

To remove a PostOffice from the array based on its ID, you can use a checkbox to select the desired element and then utilize its ID for the delete function. Here is an example: let postOffices = [ {postOfficeID: 15, postCode: '3006&ap ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

The directive isn't responding to changes in the Angular scope.watch function

I am facing an issue with my Angular directive that monitors a list and generates a custom select when the list is modified. While it works perfectly on one page, it fails to work on another page. I am unable to determine why, but it seems like the watch f ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

Leveraging a Service Property Initialized by Callback Function Across Different Components in Angular

When I try to access the myData property of a DataService in my DataComponent, it is undefined due to waiting for callback. How can I properly utilize and access this data? export class DataService { public myData; constructor(private http: HttpClien ...

When trying to access a certain class property, I was met with the following error message: TypeError: Unable to read/set property 'x' of

Lately, I've delved into the realm of JavaScript / TypeScript and decided to create a basic React App using TypeScript. Within one of my components, I aim to switch between different components using a "state" (where each component will follow the pre ...

Angular: How can I apply animation to rotate an image within a component?

Within my map application, I have implemented a component called compass component. I am seeking a way to programmatically rotate this compass with animation as the map is rotated. The solution involves utilizing angular animation. To achieve this functio ...

Traversing an array of objects to locate a specific key

I have an array of objects structured as follows: data = [ { "AccountType":"Client", "DeploymentList": { "-L3y8Kpl5rcvk-81q004": { "DeploymentKey":"-L3y8Kpl5rcvk-81q004", "DeploymentName":"Testing 3" ...

Creating a typescript object shape without an index signature involves specifying the exact properties

I have a query regarding a potential design gap in TypeScript. Consider a function that accepts objects meeting a specific interface: interface Params { [key: string]: string | number | boolean | undefined | null; } This interface specifies that the k ...

What is the best way to extract information from an array?

I am trying to retrieve a list of cat images from the CAT API. This data is coming from an API. [ { "breeds": [], "id": "bhf", "url": "https://cdn2.thecatapi.com/images/bhf.jpg", "wid ...

Implementing Dynamic Route Based Modals in Next.js

Is it possible to create a dynamic route-based modal in Next.js 13 (using the app directory)? My goal is to achieve a similar functionality to websites like nomadlist and Instagram, where clicking on a card opens a modal with an updated route, such as htt ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Regulation specifying a cap of 100.00 on decimal numbers entered into a text input field (Regex)

I have created a directive that restricts text input to only decimal numbers in the text field. Below is the code for the directive: import { HostListener, Directive, ElementRef } from '@angular/core'; @Directive({ exportAs: 'decimal ...

The React Next app is experiencing issues that are possibly related to updates within a hook

After spending the last hour frustrated and confused, I can't seem to figure out why my code is only displaying the loading spinner but never updates to show the actual data. Even though I can see the data printed in the console, indicating that the d ...

Failed to successfully sort several distinct lists using the ng2-dnd sorting library

Recently, I came across a fantastic drag-and-drop library on GitHub that I decided to use. In my current project, I have created a view with three different buttons, each revealing a list when clicked at the same position but not simultaneously. However, ...