9

Making a generator method in typescript is simple:

class Foo {
    *values() { yield 10 }
}

But I want to make a generator property, something like this:

class Foo {
    get *values() { yield 10 }
}

But that seems to be invalid. I can't seem to find any references to this question or workarounds (aside from the obvious of using Object.defineProperty explicitly, which would suck because it would be untyped). Am I missing something? Is this supported? If not, will it be?

1 Answer 1

8

You could fake it with a backing method.

class Gen {
    private *_values() {
        yield 3;
        yield 4;
    }

    public get values() {
        return this._values();
    }
}

let g = new Gen();

let v1 = g.values;
let v2 = g.values;

console.log(v1.next());
console.log(v1.next());
console.log(v1.next());
console.log(v2.next());
console.log(v2.next());
console.log(v2.next());

/* stdout
{ value: 3, done: false }
{ value: 4, done: false }
{ value: undefined, done: true }
{ value: 3, done: false }
{ value: 4, done: false }
{ value: undefined, done: true }
*/
Sign up to request clarification or add additional context in comments.

1 Comment

If only there were generator lambdas, this would be so much nicer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.