Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Generator Property / Getter

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?

like image 341
Yona Appletree Avatar asked May 12 '17 20:05

Yona Appletree


1 Answers

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 }
*/
like image 84
y2bd Avatar answered Oct 19 '22 03:10

y2bd