简体   繁体   English

Eslint 返回 no-unused-vars

[英]Eslint returns with no-unused-vars

I have setup eslint to warn me on unsed vars我已经设置了 eslint 以在 unsed vars 上警告我

rules: {
  '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }],
}

Now I have a typescript class which look like this:现在我有一个 typescript class 看起来像这样:

import { User } from './user';

export class MyClass {
  async myMethod(): Promise<User> {
    // Some code
  }
}

When I run eslint I get this error当我运行 eslint 时出现此错误

error  'User' is defined but never used  @typescript-eslint/no-unused-vars

Why is eslint warning me?为什么 eslint 警告我? In my eyes the variable is used.在我看来,使用了变量。

In your example, we see only the type Promise, which doesn't mean that you are using User in your Method, but only to define a type.在您的示例中,我们只看到类型 Promise,这并不意味着您在方法中使用 User,而只是定义一个类型。 Eslint is expected:预计 Eslint:

import { IUser} from './user'; // interface for User object
import { User } from './user'; // User object

export class MyClass {
  async myMethod(User: string): Promise<IUser> {
    // Some code with User parameter
  }
}

Your Eslint rule will apply only on User object, and not on the interface.您的 Eslint 规则将仅适用于用户 object,而不适用于界面。

some readings:https://basarat.gitbook.io/typescript/future-javascript/promise一些阅读材料:https://basarat.gitbook.io/typescript/future-javascript/promise

You must disable the base rule as it can report incorrect errors.您必须禁用基本规则,因为它会报告不正确的错误。 Reference: @typescript-eslint/no-unused-vars参考: @typescript-eslint/no-unused-vars

  "no-unused-vars": "off",
  "@typescript-eslint/no-unused-vars": ["error", { args: "none" }]

User.ts用户.ts

export class User {
    name: string;
}

MyClass.ts我的类.ts

import { User } from './User'

export class MyClass {
    async myMethod(): Promise<User> {
        // Some code
    }
}

Also this is my bare minimum eslint config这也是我的最低 eslint 配置

module.exports = {
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint/eslint-plugin"],
  "env": {
    "node": true
  },
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module"
  },
  "rules": {
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": ['error'],
  }
}

package.json dependencies package.json 依赖项

{
  "scripts": {
    "lint": "eslint hello.ts"
  },
  "devDependencies": {
    "@types/eslint": "7.2.4",
    "@types/node": "13.7.7",
    "@typescript-eslint/eslint-plugin": "4.14.1",
    "@typescript-eslint/parser": "4.14.1",
    "eslint": "7.18.0",
    "ts-node": "8.6.2",
    "typescript": "3.8.3"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM