Using `await` or `then` with a Promise object can lead to varying results

Here is an example of code that compiles successfully

import yargs from "yargs";

const parser = yargs(process.argv.slice(2)).
    usage("$0 [filename]").
    demandCommand(1);

async function main() {
    const argv = await parser.argv;
}

And here is an example where the code does not compile

import yargs from "yargs";

const parser = yargs(process.argv.slice(2)).
    usage("$0 [filename]").
    demandCommand(1);

parser.argv.then(argv => {});

This results in compile errors:

src/index.ts:13:1 - error TS18046: 'parser.argv.then' is of type 'unknown'.

13 parser.argv.then(argv => {});
   ~~~~~~~~~~~~~~~~

src/index.ts:13:18 - error TS7006: Parameter 'argv' implicitly has an 'any' type.

13 parser.argv.then(argv => {});
                    ~~~~

Based on my language server, the type of parser.argv is as follows:

(property) yargs.Argv<{}>.argv: {
    [x: string]: unknown;
    _: (string | number)[];
    $0: string;
} | Promise<{
    [x: string]: unknown;
    _: (string | number)[];
    $0: string;
}>

I initially assumed that using await on a promise object and using .then on a promise object would yield the same result. However, it seems they behave differently in Typescript. Can you explain why?

Answer №1

It appears that the variable parser.argv is not of type promise during runtime.

Even though you can use await with any value, you can only invoke .then() on a promise object (or an object with a then method).

If you want to ensure that the value is a promise, you can encapsulate it using Promise.resolve()

Promise.resolve(parser.argv).then((argv) => {
  // ...
});

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

Enhancing Angular2 Routing with Angular4 UrlSerializer for Seamless HATEOAS Link Integration

As a newcomer to Angular4, I am currently exploring how to consume a HATEOAS API. My goal is to either pass an object that contains the self reference or the self reference link itself through the routing mechanism (for example, by clicking on an edit link ...

The issue of footer overlapping the login form is observed on iOS devices while using Safari and Chrome

Unique ImageI am currently working on an Angular 8 project with Angular Material. I have successfully designed a fully functional login page. However, I am encountering a problem specifically on iOS devices such as iPhones and iPads, whether it is Safari o ...

Typescript: Shifting an image to the left and then returning it to the right

As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by s ...

Extending a generic typed class in Typescript allows for the creation of

I am interested in extending the following class: import 'reflect-metadata'; import { IRepository, IFireOrmQueryLine, IOrderByParams, IEntity } from './types'; import { AbstractFirestoreRepository } from './AbstractFirestoreReposit ...

Is it possible to retrieve a value obtained through Request.Form?

Within my Frontend, I am passing an Object with a PersonId and a FormData object. const formData = new FormData(); for (let file of files){ formData.append(file.name, file,); } formData.append('currentId',this.UserId.toString()); const upl ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

Avoiding multiple HTTP requests on various subscribers in RXJS/Angular

I am currently utilizing the "mainData" service, which is composed of 3 key parts: currentPage is utilized by the paginator component for page navigation and can be updated dynamically. folders holds all folders within the current directory. This observa ...

Is there a way to verify an if-else statement in the ngStyle background property with Angular 7?

I have a collection of cards that need to be shown in a component. Each card contains a cover-image with an URL fetched from the server. In my component.html, I am using ngFor as follows: <div [style.background-image]="'url('+row.companyId?.c ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

What is the best way to preserve all props while typing a styled component in Typescript?

I'm just starting out with styled components and I want to ensure that I can properly type my styled components so that I can easily utilize all the props I pass, not just the ones defined in the theme or through an interface. Is there a way to achie ...

Challenge with using the React useEffect hook

Incorporating the React useEffect hook into my code has been a bit challenging. Here is how I am attempting to use it: function App() { React.useEffect(() => { console.log('effect working') }, []) return ( <div className=" ...

Issue with JSON encoding in Embed message/interaction reply in Discord.js v14

I am currently utilizing Discord.js version 14.8, which was developed in typescript. Here is a snippet from my package.json file: "dependencies": { "@discordjs/rest": "^1.1.0", "@supabase/supabase-js": &quo ...

Prisma designs a personalized function within the schema

In my mongo collection, there is a field named amount. My requirement is to have the amount automatically divided by 100 whenever it is requested. In Django, this can be achieved with a custom function within the model. Here's how I implemented it: cl ...

Utilizing Rxjs to transform an array of objects

My goal is to map an array of objects. Currently, I have the following code: return this.service.post(url, payload, this.httpOptions) .pipe( map((obj: any, index) => [({ ...obj, val1: obj[index].val1.id, v ...

Eliminate any values that have not been chosen from the dropdown array in ngx-select-dropdown

Scenario: The challenge involves managing selected values in Angular applications using the ngx-select-dropdown. Users can select multiple values, which are then sorted into "buckets" and sent to the API. Problem: I'm facing difficulty removing a sel ...

Struggling to overcome the TS2322 error when assigning generic values

I am currently working on developing higher-order React components that will include default values for components labeled as "named". Here is a basic implementation example: type SomeProps = { a: string } type Variants = 'variantA' | 'var ...

Encountering issues with Next.js routing - Pages failing to load as expected

Having some trouble with the routing in my Next.js application. I've created a page named about.tsx within the "pages" directory, but when trying to access it via its URL (localhost:3000/about), the page fails to load correctly and displays: This Pa ...

Creating an interface for writing types in Firebase functions/storage/database

What are the TypeScript types for Firebase functions, storage, and admin? I'm fairly new to TypeScript and currently in the process of updating my JavaScript code to TypeScript. Within my code, I am generating a context object. const context = { ...

How to override or redefine a TypeScript class with generics

Presently, I am immersed in a project involving three.js and TypeScript. It has come to my attention that for organizing elements, the Group class is highly recommended. However, I have noticed that the type definitions for Group do not include a feature l ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...