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?
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 }
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With