Typescript: VSCode shows me "Type must have a [Symbol.iterator]() method (...) " but Type has it.

Created on 7 Oct 2015  ·  1Comment  ·  Source: microsoft/TypeScript

I can see that error with this code:

function* numIterator(num: number) {
    var n = parseInt(num.toString()).toString();
    var length = n.length;
    for (var i = length - 1; i >= 0 ; --i){
        yield n.charAt(i);
    }   
}

Number.prototype[Symbol.iterator] = function() {
    return  numIterator(this.valueOf());
}
var num = 2387;
for (var n of num){ // Error in VSCode but It works fine in Chrome
    console.log(n) // 7, 8, 3, 2
}   

Question

Most helpful comment

You are augmenting the Number interface without telling the type system about it, so it does not know that a number now has an iterator. you need to augment the declaration of interface Number to add the iterator declaration, so adding something like this to your file should get rid of the error:

interface Number {
    [Symbol.iterator](): IterableIterator<string>;
}

>All comments

You are augmenting the Number interface without telling the type system about it, so it does not know that a number now has an iterator. you need to augment the declaration of interface Number to add the iterator declaration, so adding something like this to your file should get rid of the error:

interface Number {
    [Symbol.iterator](): IterableIterator<string>;
}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

metaweta picture metaweta  ·  140Comments

fdecampredon picture fdecampredon  ·  358Comments

quantuminformation picture quantuminformation  ·  273Comments

nitzantomer picture nitzantomer  ·  135Comments

xealot picture xealot  ·  150Comments