1

I have a function which needs an iterable:

function fn(ary) {
    for (let value of ary)
        console.log(value)
}

In javascript, I would take advantage of Symbol.iterator:

function isIterable(obj) {
    // checks for null and undefined
    if (obj == null) {
        return false;
    }
    return typeof obj[Symbol.iterator] === 'function';
}

Taken from Tomas Kulich original answer.

which would lead to the next code:

function fn(ary) {
    if (!isIterable(ary)) throw 'Not iterable'

    for (let value of ary)
        console.log(value)
}

Isn't there a way to take advantage of TypeScript's typing facilities rather than using this on-the-fly function?

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
  • Possible duplicate of [Checking whether something is iterable](https://stackoverflow.com/questions/18884249/checking-whether-something-is-iterable) – jhpratt Jul 31 '19 at 21:38
  • This question is identical to the one you linked — you should just post the answer over there. – jhpratt Jul 31 '19 at 21:38
  • 1
    @jhpratt — It really is not, the referred question is about **dynamic** check in **Javascript** and mine is about **static** check in **TypeScript**. Actually, I wrote _because_ I didn't see the typescript version, and the documentation was no straight to the point. My intent is for some googler to quickly find a TypeScript solution for this issue. If you were confused, I'd invite you to edit. I don't have any idea to clarify my question further (yet). – Ulysse BN Jul 31 '19 at 21:40

1 Answers1

2

There is an Iterable type that would do just that:

function fn(ary: Iterable<any>) {
    for (let value of ary)
        console.log(value)
}

Corresponding TypeScript playground here.

Note that Iterable requires on type argument. any allows you to specifically detect just if an object is iterable, although you could go further and specify on what you would like to iterate (eg. Iterable<Number>).

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82