Using TypeScript triggers an error when checking for the presence of a promise in a Record<string, Promise>

Why does TypeScript throw an error when testing the presence of a promise in an object?

This condition will always return true since this 'Promise' is always defined.

Did you forget to use 'await'?

Should I make changes to my types?

const xRecord: Record<string, Promise<number>> = {}
const generateX = async () => {
  // long async stuff here
  return Math.random()
}

const getX = async (key: string) => {
  if(xRecord[key]){ // TypeScript error occurs here
    return xRecord[key]
  }
  return xRecord[key] = generateX()
}
const x = await getX('foo')
const x2 = await getX('foo')

Answer №1

The caution is warranted, given that a (commitment) object is constantly truthy. However, if the intention is to verify whether the xRecord possesses the key, then use:

if (key in xRecord)

Since this will also search in the object prototype chain, you might prefer to specify that you are specifically searching for a personal property:

if (Object.hasOwn(xRecord, key))

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

Can a custom type be created in Typescript that permits objects but excludes Errors?

Currently working on resolving an odd scenario with a logger. Essentially, calls like log({ info: 'information' }) function as expected, but log(new Error()) falls short. While no solution is readily available, the goal is to override the log m ...

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

Unable to fetch data from Firebase in Angular 7

I have been trying to fetch a data set from firebase database and populate my drop-down list in Angular 7. However, despite conducting extensive research, I am still unable to resolve the issue. Here is the error message that I encounter: ERROR Error: "Ca ...

What is the process of creating locale aliases in typesafe-i18n?

Motivation Throughout history, the Chinese language has been associated with multiple language codes (RFC 5646 with ISO-639 zh). The most commonly used ones include zh-CN (Simplified Hanzi Script of Chinese Mandarin primarily used in PRC, etc.), zh-TW (Tr ...

Utilizing multiple Redux states within a singular component

Seeking advice on merging multiple states into a component with TypeScript in use. I came across a discussion on this topic from 2 years ago - Multiple Redux states in a single component - Typescript, React, Redux. While I attempted the suggested solutio ...

Error in Angular 4: Unexpected 'undefined' provided instead of a stream

I encountered an issue while attempting to make a HTTP Post request. The error message I received is as follows: auth.service.ts?c694:156 Something went wrong requesting a new password, error message: You provided 'undefined' where a stream ...

Showing related data in an Angular 2 Kendo UI Grid with foreign keys

In my Angular 4 and ASP.NET CORE WEB APIs project, I have a cart system for purchase orders. There are two main calls to retrieve the PO details and the line items for a specific PO from the "Cart." The table contains related funding category IDs and proje ...

try out testing with the mock declaration in Jasmine test

My service involves loading a variable from a JavaScript file fetched from a CDN (without a typedef). To handle this, I have created a declaration for the variable: declare const externalValue: string; @Injectable() export class Service { ... Everythi ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

Encountering numerous instances of blocking scoped variables being redeclared in @types library files

I'm encountering multiple TS errors from leaflet and leaflet-editable @types that are all showing the same error but pointing to different lines in the type definition files: TS2451: Cannot redeclare block-scoped variable 'L'. My project ...

You are unable to call a function that doesn't have a proper call signature when dynamically defined, yet surprisingly it still functions as intended

Being new to TypeScript, I'm still learning the ropes, so please bear with me if I make mistakes in using this technology! The challenge I'm grappling with involves creating a flexible way to structure my application errors while allowing users ...

"Exploring the world of child components in Angular

I am looking to create a unique component structure with the following syntax: <my-component [attr1]="attr1" [attr2]="attr2"> </my-component> While the basic structure is good, I need the flexibility to render different types of templates wit ...

Tips for iterating over an array that implements either of two interfaces in TypeScript

The objective is to develop a reusable method for filtering out items from an array that implements one of two interfaces Providing a code example would be most helpful: interface IDuration { start: number; end: number; } interface IRelativeDuration ...

Error encountered: Unexpected JSON token at position 0 while executing npm start on a React TypeScript project

Whenever I attempt to execute the 'npm start' command, I encounter this strange error. Everything was functioning correctly just a few hours ago, but now it refuses to launch. Even after attempting to reinstall Typescript, the issue persists. He ...

Encountering "Object is possibly undefined" during NextJS Typescript build process - troubleshooting nextjs build

I recently started working with TypeScript and encountered a problem during nextjs build. While the code runs smoothly in my browser, executing nextjs build results in the error shown below. I attempted various solutions found online but none have worked s ...

What is the result of using `X ? A : B` in typescript?

type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2 why??? how to interpret? type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2 type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1 type SomeUnion = ' ...

Bluebird - Using return works when Promise.resolve doesn't hold up

I have a function that returns a Promise save(data) => { return mymongo.insert(data).then( (result) => { console.log('hello mongo'); console.log(result); return Promise.resolve(result); ...

Issue with WebDriver/Mocha Promise failing to meet my expectations

Recently, I've been experimenting with Web Driver and Mocha as a way to improve my testing skills. However, I'm encountering some obstacles along the way. For example, when I try to return a promise from driver.findElement(By.id('promo&apo ...

Leverage the event handler within a React Component when working with TSX tags

Is there a way to expose an event handler that is defined within a React Component in an HTML-like tag? For example: <MyComp param1="abc" param2="def" onDoSomething={this.someMethod} /> I am trying to define the onDoSomething event, but currently I ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...