Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: disallow for-in with Array types #9645

Closed
danvk opened this issue Jul 12, 2016 · 1 comment
Closed

Suggestion: disallow for-in with Array types #9645

danvk opened this issue Jul 12, 2016 · 1 comment
Labels
Out of Scope This idea sits outside of the TypeScript language design constraints Suggestion An idea for TypeScript

Comments

@danvk
Copy link
Contributor

danvk commented Jul 12, 2016

Here's a function I just wrote:

/**
 * Read a property from a nested object, e.g.
 * getIn({a: {b: 2}}, ['a', 'b']) --> 2.
 */
export function getIn(o: Object, path: string[]): any {
  for (const property in path) {
    o = o[property];
    if (!o) return o;
  }
  return o;
}

It type checks fine, but it has a bug! The for .. in should really be for .. of.

If a variable is known to have an array type, then using for .. in to iterate over it is a very strange thing to do. It will iterate over the indices, converting them to strings, and skip over any holes in the array.

I'd propose that for .. in with an Array be an error. You probably want for .. of. Or array.forEach. If you really want for .. in for some reason, you could always use Object.keys(array).forEach.

This might be better implemented as a lint rule. See palantir/tslint#1380

@mhegazy
Copy link
Contributor

mhegazy commented Jul 12, 2016

I agree this is in the realm of linting. I would recommend writing a tslint rule for this.

@mhegazy mhegazy closed this as completed Jul 12, 2016
@mhegazy mhegazy added Out of Scope This idea sits outside of the TypeScript language design constraints Suggestion An idea for TypeScript labels Jul 12, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Out of Scope This idea sits outside of the TypeScript language design constraints Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants