如何在Typescript中检测未使用的变量?

Dam*_*ica 14 lint unused-variables typescript

有没有办法在Typescript中检测未使用的变量(类似于Javascript中的ESLint)?

谢谢.

Tay*_*tay 49

从版本2.0开始,Typescript内置支持检测未使用的局部变量和参数.编译器标志如下:

   --noUnusedLocals                    Report Errors on Unused Locals.
   --noUnusedParameters                Report Errors on Unused Parameters.
Run Code Online (Sandbox Code Playgroud)

  • 如果您只想将这些作为警告怎么办? (13认同)

thi*_*ple 12

您可以改用TSLint.

https://palantir.github.io/tslint/

有一个规则:https://palantir.github.io/tslint/rules/no-unused-variable/

编辑:

虽然这有效,但我现在建议使用@Taytay提出的解决方案,如果您使用的是TypeScript 2及更高版本.


Bea*_*ith 6

您还可以通过将项目tsconfig.json文件更新为include noUnusedLocals和来检测Typescript中未使用的变量noUnusedParameters

{
  "compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
  }
}

Run Code Online (Sandbox Code Playgroud)