Skip to content

Class with 'private [Symbol.iterator]' is iterable outside of the class body #42190

Open
@ajafff

Description

@ajafff

TypeScript Version: 4.2.0-dev.20210103, seems to be a regression in 3.6, probably introduced by strictly typed generators (cc @rbuckton)

Search Terms: iteration, private

Expected behavior:

Errors like in v3.5:

Type 'C' is not assignable to type 'Iterable<string>'.
  Property '[Symbol.iterator]' is private in type 'C' but not in type 'Iterable<string>'.

Type 'D' is not assignable to type 'Iterable<string>'.
  Types of property '[Symbol.iterator]' are incompatible.
    Type '() => D' is not assignable to type '() => Iterator<string>'.
      Type 'D' is not assignable to type 'Iterator<string>'.
        Property 'next' is private in type 'D' but not in type 'Iterator<string>'.

Actual behavior:

No error on iteration inside and outside of the class body.

Related Issues: #42051 and #42104

Code

class C {
    private [Symbol.iterator]() {
        return this;
    }

    public next() {
        return {value: 'a', done: false};
    }
}

class D {
    public [Symbol.iterator]() {
        return this;
    }

    private next() {
        return {value: 'a', done: false};
    }
}


function fn() {
    for (const _ of new C()) {
    }

    for (const _ of new D()) {}
}
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions