Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

for-of detection falsely triggered on typed arrays #3148

Closed
mrkite opened this issue Aug 22, 2017 · 3 comments
Closed

for-of detection falsely triggered on typed arrays #3148

mrkite opened this issue Aug 22, 2017 · 3 comments

Comments

@mrkite
Copy link

mrkite commented Aug 22, 2017

Bug Report

  • TSLint version: 5.6.0
  • TypeScript version: 2.4.2
  • Running TSLint via: CLI

TypeScript code being linted

let func = (data: Uint8Array): string => {
  let r: string = "";
  for (let i: number = 0; i < data.length; i++) {
    r += String.fromCharCode(data[i]);
  }
  return r;
};

with tslint.json configuration:

{
  "defaultSeverity": "error",
  "extends": [
    "tslint:recommended"
  ],
  "jsRules": {},
  "rules": {},
  "rulesDirectory": []
}

Actual behavior

ERROR: test.ts[3, 3]: Expected a 'for-of' loop instead of a 'for' loop with this simple iteration

Expected behavior

No error.. you can't use for-of loops on Uint8Array or any Typed Arrays.

@IllusionMH
Copy link
Contributor

IllusionMH commented Aug 22, 2017

Looks like problem with typings provided by TypeScript since TypedArrays do implement iterator protocol (according to MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator)

UPD.
Further look shows that TS has proper typings, but requires --downlevelIteration flag if target is ES3 or ES5.

Probably flag may be added to suggest for..of only for arrays/strings.

@ajafff
Copy link
Contributor

ajafff commented Aug 23, 2017

Related to #2927 and basically a duplicate of #2021

Probably flag may be added to suggest for..of only for arrays/strings.

That would require the rule to use the type checker. If it's a type checked rule, we could instead check if --downlevelIteration is enabled or target >= ES6 in tsconfig.json and lint according to that setting. That wouldn't require a new option and you don't have to keep your configs in sync.

Unfortunately TypeChecker does not expose isArrayLikeType which would be needed to correctly implement this. Note that no-for-in-array currently has the same limitations: doesn't handle ReadonlyArray or shadowing the type Array
Exposing the necessary API(s) is tracked by microsoft/TypeScript#9879, microsoft/TypeScript#17680 and many other issues

@JoshuaKGoldberg
Copy link
Contributor

Duplicate of #2021.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants