问题描述
启动一个新应用程序,我安装了eslint并使用以下配置对其进行了配置,但是每次创建enum
时,它都已定义。甚至是胡说八道的字符串。其他变量类型(const,var,let)没有此问题。我可以禁用该规则,但是我希望它适用于实际上是真的情况。
{
"root": true,"parser": "@typescript-eslint/parser","plugins": ["@typescript-eslint"],"parserOptions": {
"project": ["./tsconfig.json"],"ecmaFeatures": {
"ecmaVersion": 6,"jsx": true
}
},"overrides": [],"extends": [
"airbnb-typescript","prettier","prettier/@typescript-eslint","plugin:@typescript-eslint/recommended-requiring-type-checking"
],"rules": {
"spaced-comment": 0,"import/prefer-default-export": 0,"@typescript-eslint/no-use-before-define": 0,"@typescript-eslint/restrict-template-expressions": [
1,{ "allowBoolean": true }
],"react/jsx-props-no-spreading": "off","react/state-in-constructor": 0,"react/require-default-props": 0,"react/destructuring-assignment": [
1,"always",{
"ignoreClassFields": true
}
]
}
}
解决方法
Tadhg McDonald-Jensen 的回答很有用,但有一点需要说明。将以下配置项直接写入.eslintrc
会报错:
{
// note you must disable the base rule as it can report incorrect errors
"no-shadow": "off","@typescript-eslint/no-shadow": ["error"]
}
以下是无阴影规则的正确示例:
{
"rules": {
"no-shadow": "off","@typescript-eslint/no-shadow": ["error"]
},}
,
请参见@typescript-eslint/no-shadow how to use 也this section of FAQ
使用方法
{
// note you must disable the base rule as it can report incorrect errors
"no-shadow": "off","@typescript-eslint/no-shadow": ["error"]
}
搜索typescript-eslint GitHub issues显示了很多人问同样的事情。
,当我使用对象的某个名称声明一个变量时,会发生此错误。我忘了把变量名放在小写而不是大写的对象名称中。像 TypeFile:TypeFile
解决方案:要解决此问题,只需将变量名称设为小写即可。
生成此 Eslint 错误的代码示例:
这是我的枚举:type-file-model.ts
public enum TypeFichier {
XML,PDF,IMAGE,ZIP
}
这是我的对象模型 app-file-model.ts
import {TypeFile} from 'app/shared/model/enum/type-file.model';
export interface IAppFile {
...
TypeFile?: TypeFile;
}
export class AppFile implements IAppFile{
constructor(
...
public TypeFile?: TypeFile
) {}
}
,
似乎将此添加到基本“规则”还不够,我不得不在覆盖下再次添加它
# eslintrc.js
{
"rules": { // Did not work here as intended
"@typescript-eslint/dot-notation": "error","no-shadow": "off",},"overrides": [
{
"files": [
"*.ts"
],...
"rules": { // Here it worked
"@typescript-eslint/dot-notation": "error",}
]
}
,
我在 TypeScript 中的以下代码遇到了类似的问题:
export enum MyEnum {
myValueOne = 'myValue',myValueTwo = 'myValueTwo',// <-- got "already declared in the upper scope” error
}
export class myValueTwo {
constructor(){}
}
不幸的是,rules
或 overrides
都没有解决问题
{
"rules": {
"no-shadow": "off","@typescript-eslint/no-shadow": ["error"]
},"overrides": {
"no-shadow": "off",}
在花了几个小时检查了有关该问题的不同问题、问题和文档后,我发现了 @typescript-eslint/no-shadow
的官方文档。 Here is the link
我必须做的是在 eslint 中为 ignoreTypeValueShadow
添加额外的 @typescript-eslint/no-shadow
选项。
我对无阴影的最终设置如下所示:
{
"overrides": {
"no-shadow": "off","@typescript-eslint/no-shadow": ["error",{ "ignoreTypeValueShadow": true }]
},}