Creating and incorporating a generator function within an interface and class: A step-by-step guide

In vanilla JavaScript, the code would look something like this:

class Powers {
  *[Symbol.iterator]() {
    for(let i = 0; i < 10; i++) 
      yield { i, pow: Math.pow(i, i) }
    return null;
  }
}

This can then be utilized in the following manner:

const powers = [...new Powers()];

What should a Typescript interface look like in order to define this? Referring to the documentation here, I started with the below snippet:

interface PowGen {
  //where should the * go?
  [Symbol.iterator]: () => Generator<any, any, any>
}

Using "any" extensively resolves many compiler errors, but raises concerns about the correctness of my approach. In addition to [Symbol.iterator], the Iterator<> and Generator<> Interfaces specify a next, return, and throw method. Do these need to be implemented as well?

class Powers implements PowGen {
  *[Symbol.iterator]():Generator<any, any, any> {
    for(let i = 0; i < 10; i++) 
      yield { i, pow: Math.pow(i, i) }
    return null;
  }
}

A more detailed example or explanation, slightly more elaborate than the documentation, would greatly assist me."

Answer №1

The solution was partially embedded within the question itself.

The required setup is as follows:

type ResultType = { type: 'result' };
type EndType = null;
type ContinueNext = true | undefined;

interface Bar {
  [Symbol.iterator]: () => Generator<ResultType, EndType, ContinueNext>
}

Now for the Execution:

class Baz implements Bar {
  *[Symbol.iterator] () : Generator<ResultType, EndType, ContinueNext> {
    const 
      elements = [ { type: 'result' }, … ], // this list is quite long
      length = elements.length
    ; 

    let 
      index = 0, 
      finish = undefined
    ;

    while (index < length && && finish === undefined) {
      finish = yield elements[index];     
      index++;
    }

    return null;
  }
}

Given that ContinueNext can accept values like undefined, utilizing the spread operator on an instance of Bar is feasible. Therefore:

let 
  bar = new Bar(),
  firstElement = bar[Symbol.iterator]().next(true).value // halts the generator
;

or

let items = [...new Bar()];

are both valid options.

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

How can we stop the parent modal from closing if the child component is not valid?

I have a main component with a modal component that takes another component as a parameter. The child modal component has some logic where I need to check if the child component is valid before closing the modal. const MainComponent: FC<IProps> => ...

The interaction between Nextjs router and useEffect resulting in unintended re-rendering

I'm currently facing a challenge with Next.js's next/navigation router. In my component, I have a series of useEffects implemented. Strangely, when I call router.replace, one of the effects runs twice or even infinitely in some cases. As a result ...

Before running any unit tests, I have to address all linting issues as required by ng test

Upon running ng test, the output I receive is as follows: > ng test 24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/ 24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ ...

Creating a Mocha+Chai test that anticipates an exception being thrown by setTimeout

Here is what I have: it('invalid use', () => { Matcher(1).case(1, () => {}); }); I am trying to ensure that the case method throws an exception after a delay. How can I specify this for Mocha/Chai so that the test passes only if an exce ...

Securing Angular 2 routes with Auth Guard through canActivate

I've been searching for a solution to this problem for the past 4 hours with no luck. I have multiple Authguards set up, and I want to instruct the router to grant permission if any of them are true, rather than requiring all guards to be true. Curre ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

Sending information from a parent component to a child component within an Angular application

How can I efficiently pass the this.formattedBookingPrice and this.formattedCheckingPrice values to a child component using the value array instead of static values, especially when they are inside the subscribe method? This is my parent component. expor ...

Specify the correct type for the SVG component when passing it as a prop

Currently, I am in the process of constructing a button component: interface ButtonProps { startIcon?: ... <-- what should be the data type here? } const Button = ({startIcon: StartIcon}) => { return <button>{StartIcon && <Sta ...

Discovering the data types for node.js imports

When starting a node.js project with express, the code typically begins like this - import express = require('express') const app = express() If I want to pass the variable 'app' as a parameter in typescript, what would be the appropri ...

Please provide either a string or an object containing the proper key for TypeScript

Within my project, the languageSchema variable can either be a string or an object containing the 'Etc' key. The corresponding interface is defined as follows: let getLanguageSchema = (language: string): string => languagesSchemas[language]; ...

Retrieve information from an XML document

I have some XML content that looks like this: <Artificial name="Artifical name"> <Machine> <MachineEnvironment uri="environment" /> </Machine> <Mobile>taken phone, test when r1 100m ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

What is the significance of an equals sign being located within the angle brackets of a type parameter?

Within the type definitions for Bluebird promises, there is a catch function that has the following definition: catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>; The symbol "R" is derived fr ...

Webpack, TypeScript, and modules are set to "esnext," resulting in a change to undefined

In my setup, I am using webpack with typescript (via ts-loader). To enable code splitting in webpack, it is necessary to adjust the module setting to esnext in the tsconfig file: // tsconfig.json { "compilerOptions": { "module": ...

Having issues with TypeScript custom commands in Cypress?

Update: https://github.com/cypress-io/cypress/issues/1065#issuecomment-351769720 Removing an import from my commands.ts fixed it. Thanks In the process of transitioning my cypress project to use TypeScript, I am following the guidelines provided at https: ...

Transforming an array of elements into an object holding those elements

I really want to accomplish something similar to this: type Bar = { title: string; data: any; } const myBars: Bar[] = [ { title: "goodbye", data: 2, }, { title: "universe", data: "foo" } ]; funct ...

Should the PHP interface be exported to a Typescript interface, or should it be vice versa?

As I delve into Typescript, I find myself coding backend in PHP for my current contract. In recent projects, I have created Typescript interfaces for the AJAX responses generated by my backend code. This ensures clarity for the frontend developer, whether ...

Tips for invoking both a typescript arrow function and a regular javascript function within one event

Is it possible to call both a JavaScript function and a TypeScript function from the same onClick event in a chart? I am new to TypeScript and Angular, so I'm not sure if this is achievable. The issue at hand is that I need to invoke a JavaScript fun ...

Dealing with performance issues in React Recharts when rendering a large amount of data

My Recharts use case involves rendering over 20,000 data points, which is causing a blocking render: https://codesandbox.io/s/recharts-render-blocking-2k1eh?file=/src/App.tsx (Check out the CodeSandbox with a small pulse animation to visualize the blocki ...

Displaying notification in Ionic 2

Whenever I click on the register button, if I fill out all the fields I am taken to the regsuccess page. Otherwise, I receive a message saying to fill in all required fields. However, I want to display an alert message using Ionic2 and TypeScript. HTML: ...