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

'expected variable-declaration to have a typedef' lint error on for loops #3912

Closed
janez-svetin opened this issue May 15, 2018 · 1 comment
Closed

Comments

@janez-svetin
Copy link

janez-svetin commented May 15, 2018

Bug Report

  • TSLint version: 5.10.0
  • TypeScript version: 2.7.2
  • Running TSLint via: CLI

TypeScript code being linted

// code snippet (for-loop.ts file)
const split = [ 1, 2, 3, 4, 5 ];
for (let i = 0; i < split.length; i += 1) {
  console.log("Foo Bar!");
}

with tslint.json configuration:

{
  "extends": [
    "tslint-eslint-rules"
  ],
  "rulesDirectory": [
    "node_modules/codelyzer"
  ],
  "rules": {
    "typedef": [
      true,
      "variable-declaration"
    ]
  }
}

Actual behavior

ERROR: test-for-loop.ts[1, 7]: expected variable-declaration: 'split' to have a typedef
ERROR: test-for-loop.ts[2, 10]: expected variable-declaration: 'i' to have a typedef

Expected behavior

The typedef rule should ignore variables declared within for loop declarations.

Looking at the source, typedefRule.ts line 176, there is condition written:

if (parent.kind === ts.SyntaxKind.CatchClause
    || parent.parent.kind === ts.SyntaxKind.ForInStatement
    || parent.parent.kind === ts.SyntaxKind.ForOfStatement) {
  return;
}

I think it should also include basic ForStatement kind:

if (parent.kind === ts.SyntaxKind.CatchClause
    || parent.parent.kind === ts.SyntaxKind.ForInStatement
    || parent.parent.kind === ts.SyntaxKind.ForOfStatement
    || parent.parent.kind === ts.SyntaxKind.ForStatement) {
  return;
}

In this case it does not falesly reports on 'i' to have typedef.

Any specific reason it is left out?

@jkillian
Copy link
Contributor

TypeScript actually doesn't allow a type annotation on the LHS of for-in or for-of loops, so the typedef rule must not check for one there. Since a regular for loop can contain an arbitrary initializer, it makes sense to check for a type declaration there.

I think the real issue here is that the typedef rule isn't great and often leads to overly-verbose code. See #711 for somewhat related discussion. What'd be best here may be to let typedef ignore simple declarations like let i = 0 all together.

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

No branches or pull requests

2 participants