Declaration in Typescript for an array of strings that will be returned as a

I am facing an issue with my async function that is supposed to return either a single string or an array of strings. Here is the relevant code snippet:

   async getAllAnnotationTimes(): Promise<string> | Promise<string[]> {
         return await this.app.client.getText(this.allAnnotationPositions);
   }

In addition, I have also tried using the following declaration:

Promise<string> | Promise<Array<string>>

However, it resulted in this error message:

[ts] The return type of an async function or method must be the global Promise<T> type.

The error seems to be related to the section after the or, particularly with

Promise<Array<string>>

Could someone please advise on how to correctly declare a promise for a string array?

Answer №1

For this scenario, the appropriate method to employ is:

Promise<string | string[]>

What this signifies is a promise that can resolve with either a single string value or an array containing multiple strings.

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

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: My intention was to have the menu displayed below the content page while keeping the menu button visible. However, when I ran my app, it appear ...

How do I designate the compiled migration location?

Currently, I am utilizing the PostgreSQL database ORM Sequelize along with TypeScript as a backend script within the Express Node.js environment. My first inquiry is: Is it possible to directly create a model in .ts format? The second question pertains t ...

Steps for assigning a value from an enumerated type

I searched extensively online and came across resources like this: https://www.typescriptlang.org/docs/handbook/enums.html, but none provided an answer to my specific inquiry. Within the enum generated by typescript-generator, I have the following: type ...

Display the React component following a redirect in a Next.js application that utilizes server-side rendering

Just starting out with next.js and encountering a problem that I can't seem to solve. I have some static links that are redirecting to search.tsx under the pages folder. Current behavior: When clicking on any of the links, it waits for the API respo ...

Handling mouse events with Angular 2 (tracking movement based on current position)

One of the features I want to implement for my user is the ability to move or rotate an object in a canvas using the mouse. The process involves calculating the delta (direction and length) between successive mouse events in order to update the position of ...

Stop the instantiation of type alias

Is there a way to restrict the creation of an instance of a type alias, such as ValidatedEmail? type ValidatedEmail = { address: string; validatedOn: Date } Let's say we have functions validateEmail and sendEmail. const validateEmail = (email): Valid ...

Connect the keys from one enum to either keys or values in another enum

When working with the code below, it is important that the keys of PropertiesNamesInDataBase align with those in User.Keys. While the values of PropertiesNamesInDataBase are used in the backend, it is crucial for uniformity that the names match in the fron ...

Array that provides specific data types for indexes

Could be a tricky question or maybe not feasible, but I've been scratching my head over it for quite some time and just can't seem to crack it. Appreciate any help! The T generic creates a union type: const arrayToArray = <T>(values: T[]) ...

How can I integrate a timer into an Angular carousel feature?

I have put together a carousel based on a tutorial I found on a website. Check out the HTML code for my carousel below: <div class="row carousel" (mouseover)="mouseCheck()"> <!-- For the prev control button ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

During rendering, the instance attempts to reference the "handleSelect" property or method which is not defined

I've incorporated the Element-UI NavMenu component into my web application to create a navigation bar using Vue.JS with TypeScript. In order to achieve this, I have created a Vue component within a directory called "navBar," which contains the follow ...

Why does TypeScript not recognize deconstructed arrays as potentially undefined variables?

When looking at the code snippet below, I was under the impression that the destructured array variables, firstName and lastName, would be classified as string | undefined. This is because the array being destructured could have fewer variables compared ...

How can you partially update an entity in TypeORM using a query runner?

Updating a user's name partially is simple with the repository save method: await this.repository.save({ id: 1, name: 'john' }); However, when attempting to do the same using queryrunner, all fields must exist which throws an error stating ...

Is it possible to use the HostListener in Angular 7 to detect any scroll event occurring on a specific element within a webpage?

I am developing a breadcrumb bar component in Angular 7 that should dynamically hide and show based on user scrolling behavior. To achieve this, I created a directive to track the scroll position of the container element. While my code for capturing the s ...

Convert JSON data to an array using Observable

My current task involves parsing JSON Data from an API and organizing it into separate arrays. The data is structured as follows: [ {"MONTH":9,"YEAR":2015,"SUMAMT":0}, {"MONTH":10,"YEAR":2015,"SUMAMT":11446.5}, {"MONTH":11,"YEAR":2015,"SUMAMT":5392 ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

TypeScript function encountering issues with proper evaluation of set iteration

Whenever I attempt to run the code below, I consistently receive this console message: "undefined is not an object (evaluating 'this.courseAvailThisTerm')". Even though the courseAvailThisTerm() function functions properly in other scenarios. Any ...

Unveiling the proper extension of component props to default HTML button props

Currently, I am in the process of developing a button component that includes a variant prop to specify its color scheme. Below is a simplified version of the code: interface Props extends React.HTMLProps<HTMLButtonElement> { variant: 'yellow ...

Creating test cases for a service that relies on a Repository<Entity> to consume another service

Having trouble creating tests for an auth.service that seems pretty straightforward from the title. However, every time I run the tests, I encounter this error: TypeError: Converting circular structure to JSON --> starting at object with cons ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...