I am currently working on extending the functionality of Iterable
by adding a where method, similar to C#'s Enumerable.where()
. While it is straightforward to extend the Array
prototype, I am encountering difficulties in figuring out how to extend an Iterable
.
Here is the declaration I have so far:
declare interface Iterable<T> {
where<T>(this: Iterable<T>, predicate: (item: T) => boolean): Generator<T>;
}
The issue lies with the implementation. Although the extended method compiles without errors, when attempting to utilize this method on an Array
(which is an Iterable
) or any Iterable
, a runtime error is thrown indicating that where()
is not defined. For an Array
, one would typically add the method implementation to Array.prototype
. However, Iterable
does not have a prototype:
function* where<T>(this: Iterable<T>, predicate: (item: T) => boolean): Generator<T> {
for (const item of this) {
if (predicate(item)) {
yield item;
}
}
}
Attempting
Iterable.prototype = function* where(...)
is unsuccessful because Iterable
does not possess a prototype.
Here is how I envision using this functionality:
public myMethod(myIterable: Iterable<number> ) {
console.log(myIterable.where(i => i > 3));
}
How can I effectively extend Iterable
? Should I consider extending IterableIterator
instead?
I came across a solution in another thread (https://stackoverflow.com/questions/62008192/typescript-`extending`-iterableiterator-for-array-type-but-return-a-simple-type), but the individual did not provide details on extending Iterable and recommended me to post a separate question for further assistance.