Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that I can't quite decipher. This error seems to imply something about the 'next' method of the iterator expecting type 'undefined' but receiving 'unknown'. How should I tackle this issue while still being able to yield the contents of the array?

TS2766: Cannot delegate iteration to value because the 'next' method of its iterator expects type 'undefined', but the containing generator will always send 'unknown'.

Edit: Here's the full code snippet for the problematic generator function:

  /**
   * Returns an iterator that loops over caught events
   * @yields Promise<Event|CustomEvent>
   */
  async *on(eventName: string, options?: AddEventListenerOptions): AsyncGenerator<Event> {
    if (this.#eventsListened.has(eventName)) {
      return;
    }
    let results: Event[] = [];

    let resolve: (value?: PromiseLike<Event> | Event) => void;

    let promise = new Promise<Event>(r => (resolve = r));
    let done = false;
    this.#eventsListened.add(eventName);

    if (typeof options === 'object' && typeof options.once !== 'undefined') {
      throw new Error('options.once is not supported. Use EventTarget2.once instead');
    }
    const callback = (evt: Event) => {
      results.push(evt);
      resolve();
      promise = new Promise<Event>(r => (resolve = r));
    };

    this.addEventListener('eventName', callback, options);
    while (!done) {
      await promise;
      yield* results;
      results = [];
      done = !this.#eventsListened.has(eventName);
    }
    this.removeEventListener(eventName, callback);
  }

Answer №1

The issue lies in your use of AsyncGenerator<Event>. Since you did not provide the third generic parameter, it defaults to unknown, which does not match undefined.

This mismatch occurs because the inner iterator does not expect any values passed into the iterator via next(value), so its TNext generic parameter is undefined. When you use yield* with that iterator, calling next(...) on your generator's iterator will pass the same arguments to the inner iterator, hence they must match.

Typescript automatically infers the type of a generator function as

AsyncGenerator<..., ..., undefined>
for this reason. To resolve this, you should explicitly specify the type if you do not plan on passing values into the iterator with .next:
AsyncGenerator<Event, void, undefined>
.

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 is the best way to implement a Promise Function within a For loop?

Here is a function called sendEmail: public async sendEmail (log: LogMessage): Promise<void> { nodemailer.createTestAccount(async () => { return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => ...

The process of combining identical data values within an array of objects

Can anyone help me with merging arrays in JavaScript? Here is an example array: [{ "team": team1, "groupname": "group1", "emp-data": [{ "id": 1, "name": "name1", }], }, { "team": team1, "groupname": "group1", " ...

Establishing the default selection and deactivating the notification

I've been struggling for a while to make this function properly. My knowledge of jquery and javascript is limited, so I'm facing some challenges. What I'm aiming to do is to have a default option selected from the drop-down menu when the but ...

Tips for handling arguments in functional components within React applications

Is it possible to pass arguments to a function in a functional component without creating the function directly in JSX? I've heard that creating functions in JSX is not recommended, so what's a better way to achieve this? function MyComponent(pr ...

Create a filter system using a MERN stack that incorporates regex, a search box,

In an effort to understand how the MERN stack operates as a cohesive unit, I have taken on a hands-on approach by following tutorials from bezcoder. These include guides on Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code). Sam ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

What could be causing textbox2's value to not update when textbox1's value is changed? (Novice)

I am looking to create an interactive form with two textboxes and a checkbox. When the checkbox is checked, I want the value of textbox2 to mirror whatever is typed into textbox1. Is there a way to have the value of textbox2 automatically updated when the ...

Implementing i18n in NextJS with a focus on maximizing SEO performance

My task was to implement internationalization (i18n) for our company website. Currently, we are using Netlify with @netlify/plugin-nextjs, and I encountered an issue when trying to submit a PR. An error popped up stating: Error: i18n support is not compati ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

Using Typescript: Defining a property's type based on the value of another property in the same object

I'm dealing with a TypeScript interface that consists of two properties (type:string and args:object). The contents of the args property may vary based on the value of the type. I'm looking for the correct type definition to specify for the args ...

Is there a way to have my code run a script only once right after a component has finished loading?

I am currently developing a web application using Vuejs and implementing the vue-router with single file components. One issue I am facing is that whenever a user navigates to a specific route, the created() function within the component gets triggered. T ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

What is the best way to prevent the first option in a <select> element from moving up and down using jQuery?

Is there a way to make the first option in a select list non-selectable and keep it at the top when using up and down buttons? The value option should always remain on top. If "Author" is selected and the up button is clicked, nothing should change. The ...

`problem with moment.js incorrectly identifying the day of a given date`

I'm currently working with a field that has the value 03-01-2020, which is in the DD-MM-YYYY date format. However, when I apply the code moment.utc(document.getElementById('date').value, "DD-MM-YYYY HH:mm:ss").toDate(), I noticed that the re ...

Saving resources with a promise in Angular

I am facing a challenge while trying to handle a promise from the angular $resource save function. According to the documentation, I should be able to access the raw $http promise by using the $promise property on the returned object. Here is an example: ...

Is there a way to stop a specific route in Express from continuing further execution without completing its function?

In my post route, I need to ensure that the user has provided all the necessary data in the body. To achieve this, I have added an if block to check for errors. router.post("/", (req, res) => { if(req.body.age < 24) { res.send("You are too you ...

What is the proper way to include a closing tag for the canvas in a Canvas rendered by Three.js

Why does three js always add canvas elements without a closing tag to the page? Is there a specific reason for this? I'm interested in adding a closing tag to this canvas element. This example page was inspected, revealing something similar to this ...

Exploring the Positives and Negatives of Using JQuery and Glow JavaScript Libraries

Is there a detailed analysis available that compares JQuery with the BBC's Glow JavaScript libraries? ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...