typescript-eslint: [indent][meta issue] Problems with the indent rule

STOP! DO NOT FILE ANY NEW ISSUES ABOUT THE INDENT RULE

Your specific indent bug might not have an issue created. That does not matter. Don’t file a new issue. If you raise an issue we will just close it and reference this issue. Please don’t waste our time by doing that.

The rule is broken and telling us different ways in which it is broken doesn’t change the fact that it is broken.

For the same reason - please don’t comment on this issue with bug reports.


TL;DR - the indent rule is broken on TypeScript codebases. Due to bandwidth constraints it will remain broken indefinitely unless the community is able to step up to fix it.

The Problem

Many of you that have used our indent extension rule have quickly run into problems with it.

It incorrectly handles many cases that seem trivial, or it handles a block of code in one form, but breaks when you put in a new line. There are unfortunately a myriad of issues with it.

So when I first implemented it over a year ago (https://github.com/bradzacher/eslint-plugin-typescript/pull/219), I took a very naive approach to solving the problem - I made TypeScript nodes look like JavaScript nodes, and called existing handlers in the base rule’s implementation.

This worked well enough for simple cases, but was quickly discovered to be a terrible solution due to the complexity of TypeScript and the myriad ways in which its constructs can be nested and combined, and also in how users expect each combination to be indented by default.

So I began the process of forking the base rule codebase by copying it over and adding types (#439). I had grand plans to implement every single TypeScript node in this fork, so we could support it fully. This was another naive thought, as it quickly dawned on me how complex the rule’s implementation is, and how difficult it is to handle every single variation of each node.

For example, take a simple union type:

   type T = foo | bar
//          ^^^^^^^^^ expected indent = 0

   type T = foo
//          ^^^ expected indent = 0
     | bar
//   ^^^^^ expected indent = 1

   type T = 
     foo
//   ^^^ expected indent = 1
     | bar
//   ^^^^^ expected indent = 1

   type T =
     | foo
//   ^^^^^ expected indent = 1
     | bar
//   ^^^^^ expected indent = 1
    
   type T = | foo
//          ^^^^^ expected indent = 0
     | bar
//   ^^^^^ expected indent = 1

Then there’s the notion of configurability for this, which add more complexity.

The base rule has had ~5 years to grow via the community (though it was mostly a few dedicated contributors) - a community that actively uses the rule, and has motivation to use the rule because the problems cause issues for them.

A few years ago, I (like most of the maintainers) made the switch for all of my projects across to prettier. For me, this was spurred by my move to working at facebook, and learning to love the package and everything it does. This means that I haven’t used the rule since then, and I have no personal motivation as a volunteer maintainer to spend the many hours it will take to build this out, and as a maintainer there are many higher-priority issues (such as parsing perf) that need attention.
As such, the rule has languished, and many issues are open.

The Solution

The rule is in a broken state. Many users are working around it via ESLint disable comments, and configuring certain nodes as ignored; both of which are poor experiences.

We as maintainers have our hands full maintaining other core infra as well as triaging issues and reviewing PRs, so we don’t have the bandwidth to take on this project.

We’d love it if some members of the community could help us out here by submitting some PRs to support TS nodes in the rule fork. Unfortunately, without some champions, the rule will not progress forward or be fixed.

Not to discourage anyone, but as a forewarning: there are some 2,100 lines of code already, and that just constitutes the typechecked fork of the base rule. The codebase contains some rather complex algorithms, and has a lot of moving parts. It will be no small undertaking to understand what it’s doing, and how it’s doing it.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 215
  • Comments: 47 (6 by maintainers)

Commits related to this issue

Most upvoted comments

I’ve sort of fixed this with a band-aid for decorated class properties and function params:

{
  // ...
  "rules": {
    // ...
    "indent": "off",
    "@typescript-eslint/indent": [
      "error",
      2,
      {
        "ignoredNodes": [
          "FunctionExpression > .params[decorators.length > 0]",
          "FunctionExpression > .params > :matches(Decorator, :not(:first-child))",
          "ClassBody.body > PropertyDefinition[decorators.length > 0] > .key"
        ]
      }
    ]
  }
}

Now you don’t need to ignore these cases on a per-file basis:

@Controller('/something')
export class SomeController {
  @Post()
  async doSomething (
    @Body() body: DoSomethingBodyDto,
+   @Query() query: DoSomethingQueryDto
-     @Query() query: DoSomethingQueryDto
  ): Promise<unknown> {
    // ...
  }
}
export class Entity {
  @PrimaryKey()
+ id!: string
-   id!: string

  @Property()
+ amount!: number
-   amount!: number
}

As a temporary solution for indent rule being in a broken state, I decided to create a plugin that brings the built-in TypeScript formatter to ESLint (which I find to be working great!).

You can access it through npm: https://www.npmjs.com/package/eslint-plugin-typescript-formatter

I hope this can help someone, cheers!

We use Prettier.

Workaround to ignore this issue:

        "@typescript-eslint/indent": [
          "error",
          2,
          {
            "ignoredNodes": [
              "PropertyDefinition[decorators]",
              "TSUnionType"
            ]
          }
        ],

Any other “ignoredNodes” to add ?

As a temporary solution for indent rule being in a broken state, I decided to create a plugin that brings the built-in TypeScript formatter to ESLint (which I find to be working great!).

You can access it through npm: https://www.npmjs.com/package/eslint-plugin-typescript-formatter

I hope this can help someone, cheers!

@mb21 as I said earlier, you probably had some other default, that got overridden by adding custom @typescript-eslint/indent.

According to the source code of typescript-eslint rules, the default value for @typescript-eslint/indent is the following:

'@typescript-eslint/indent': ['error', 4, {
   // typescript docs indent the case from the switch
   // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#example-4
   SwitchCase: 1,
   flatTernaryExpressions: false,
   ignoredNodes: [],
}],

Came from here: https://github.com/typescript-eslint/typescript-eslint/issues/608

So if you want to merge the default behavior, with decorators fix, you need the following configuration:

{
  "parser": "@typescript-eslint/parser",
  "extends": [
    "standard",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended"
  ],
...
  "rules": {
    "indent": "off",
    "@typescript-eslint/indent": ["error", 2, {
      "SwitchCase": 1,
      "flatTernaryExpressions": false,
      "ignoredNodes": [
        "PropertyDefinition[decorators]",
        "TSUnionType",
        "FunctionExpression[params]:has(Identifier[decorators])"
      ]
    }],

SwitchCase: 1 is what forces the indent for case within switch. A weird way to fix the standard behavior tbh.

Why is every comment being marked as off-topic? As far as I can tell, they are very much on-topic…

Just a note for those who (like me) have the same problems with generic function calls as described in the last post - I almost overlooked the workaround linked to in https://github.com/typescript-eslint/typescript-eslint/issues/1824#issuecomment-678640058, and this seems to work for now:

'@typescript-eslint/indent': ['error', 2, {
  ignoredNodes: ['TSTypeParameterInstantiation']
}]

image

are there any documents about type names of ignoredNodes? I want to ignore the union-type issue. but I cannot find the way.

As part of the hypothetical rewrite, I’d upstream it to eslint as a new rule indent-strict (or something), with the intention of them deprecating indent.

The indent rule is in a really weak state right now because it has maintained backwards compatibility for a long time, so there are things it doesn’t enforce at all.

Eg this is valid according to the rule, because backwards compatibility

const x = 1 &&
                           2 &&
3;

repl


There’s little difference between the ASTs provided by typescript-estree and babel-eslint. There’s a few minor inconsistencies, but IIRC most of those are things to be fixed on the babel side, and don’t have a huge impact on lint rules.

This does not solve the rule, but at least I’d like to share my solution I’ve working in this weekend.

For my purpouses, this does great indentation, at least for my codebase, we could extend the rule to add more ‘cases’, but I guess most of the normal code is covered.

Note that this rule have no other configurations aside for being turned on/off, and it is a little bit opinionated, it can be tuned to expose some configuration to ESLint to use indentation level (1,2,3,4… spaces or tabs), so it does assume you’ll use 2 indentation spaces (not tabs).

As you may notice, I’m short of time, but I could expend more time working on it to make it more customizable, but maybe at the end of this month. That why I’m creating a gist rather than a repo.

https://gist.github.com/DarkRoku12/247defa56ac6475043a42145d51ab013

The gist file itself is indented with that rule (no other indentation rules are enabled).

It should support both JavaScript and TypeScript, since my project is in TypeScript.

Hope I can help somebody with this.

That’s understandable wanting to dampen the noise of workarounds to this issue. However, you are requesting people not open separate issues for specific cases with the indent rule. That’s fine but stackoverflow is not the solution, that is where people go to solve solutions to their problems assuming the code is working correctly, which respectfully, is not yet the case.

Imagine react had a feature that didn’t function correctly, posting an issue on GH would be the most logical response, not going to stack overflow, because people on SO are not going to fix the issue. And since you are requesting no issues be opened around specific cases that leaves people to comment on this issue.

Would you be open to enabling the GH discussions tab and directing people there to discuss interim solutions to specific cases? This would also give you all an idea of issues sill needing fixes without having to search SO.

We don’t hugely want this to be a support thread for people to trade hacks about ways to ignore things to satisfy the rule. A support forum like stackoverflow would be a better place to ask for, and discuss that, and it would be more searchable there as well.

Ultimately people asking for help or posting hacks just creates noise for us maintainers - we can’t help you ourselves. But because we want to know if someone actually wants to work on improving the rule, we need to keep subscribed to this issue.

So collapsing all the comments is intended to discourage people from using this as a dumping ground to help keep the issue high signal for us maintainers.

Here’s my 3 cents:

Example 1: Incorrectly marked as incorrect, but correct for the config I gave it (all defaults for the indent rule):

const fn = (): string[] => ['foo', 'bar']
  .filter(Boolean)
  .map<string>(child => {
    console.log('It wants to unindent here');
    return child;
  });

Example 2: This is not marked as incorrect:

const fn = (): string[] => ['foo', 'bar']
  .filter(Boolean)
  .map(child => {  // Missing generic type now!
    console.log('It DOESN\'T want to unindent here now');
    return child;
  });

Example 3: It wants me to make it into this atrocity:

const fn = (): string[] => ['foo', 'bar']
  .filter(Boolean)
  .map<string>(child => {
  console.log('It thinks this is okay...');
  return child;
});

So it has to do with interpreting typescript stuff specifically. Worse is that example 3, leaving out the generic type again, is marked as incorrect again, and it wants me to make it into example 2.

This is not a discussion thread support chat. You are emailing everyone watching this issue when you reply.

One of the common issues - class method parameter decorators:

export class Foo {
  bar(
  @Request() req: any,   <--
    @Body() body: any,
    @Query() params: any,
  ) {
    ...
  }

Can be ignored by adding "FunctionExpression[params]:has(Identifier[decorators])" to the ignoredNodes list.

ignoredNodes accept a custom AST selector, and selectors are quite powerful. The given selector disables rule for the entire function params section if any of them contain a decorator. If that is too much, another :not() pseudo selector may be applied to disable the behavior for any of the nested nodes.

I have a problem using the generics method:

class SomeClass {
	test(): Observable<any> {
		return this.http
			.get<Test[]>(`test`, {
			headers: { authorization: 'some value' },
		});
	}
}

should be:

class SomeClass {
	test(): Observable<any> {
		return this.http
			.get<Test[]>(`test`, {
				headers: { authorization: 'some value' },
			});
	}
}

but when I remove generics from method - issue disappears:

class SomeClass {
	test(): Observable<any> {
		return this.http
			.get(`test`, {
				headers: { authorization: 'some value' },
			});
	}
}

Hello, given that this page mentions the following:

Per ESLint’s 2020 Changes to Rule Policies blog post, ESLint itself has moved away from stylistic rules, including formatting rules:

Stylistic rules are frozen - we won’t be adding any more options to stylistic rules. We’ve learned that there’s no way to satisfy everyone’s personal preferences, and most of the rules already have a lot of difficult-to-understand options. Stylistic rules are those related to spacing, conventions, and generally anything that does not highlight an error or a better way to do something.

We support the ESLint team’s decision and backing logic to move away from formatting and stylistic rules. With the exception of bug fixes, no new formatting- or stylistic-related pull requests will be accepted into typescript-eslint.

Is fixing this rule still being worked on / actively supported?

Thanks in advance.

@sagrawal31 Yeah, ignoring stuff will sadly lead to some errors not showing. I don’t have a workaround for that, and I’m not sure one exists until this issue here is properly resolved somehow, which I wouldn’t expect any day soon judging by the first post.

Someone from this project would probably know better than me, but it seems to me that this issue is the big catch-all issue for all indent problems, so I’d assume no other bug issue should be raised.

@IMalyugin ah, I see… thanks a lot! working great 🥳

@IMalyugin no, we have a .eslint.json file with:

{
  "parser": "@typescript-eslint/parser",
  "extends": [
    "standard",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended"
  ],

...
  "rules": {
    "indent": "off",
    "@typescript-eslint/indent": ["error", 2, {"ignoredNodes": ["FunctionExpression[params]:has(Identifier[decorators])"]}],

and the error is clearly from typescript-eslint:

error  Expected indentation of 2 spaces but found 4  @typescript-eslint/indent

🤷

Any other “ignoredNodes” to add ?

TSTypeParameterInstantiation TSIntersectionType

GH provides very little control over its discussions feature - so we cannot really add any restrictions - it’s either “on” or “off”.

If we had the bandwidth to moderate discussions and provide that level of user-support - we would definitely enable discussions. But as volunteer maintainers with very limited time - we cannot commit to that - it takes all our time to just manage issues and PRs.

In case anyone else finds this useful, I had to disable 4 types of nodes to get @typescript-eslint/indent accepting all of prettier’s TypeScript output:

'@typescript-eslint/indent': [
  'error',
  2,
  {
    ignoredNodes: [
      // Generics are not properly indented
      'TSTypeParameterInstantiation',
      'TSInterfaceHeritage',

      // Intersected types not always properly indented
      'TSIntersectionType',

      // 'implements' and 'extends' keywords sometimes improperly indented
      'ClassDeclaration'
    ],
    SwitchCase: 1
  }
]

Yes, @TobiasWehrum. It’s preventing the error for any parameter which is having a decorator. Here is the expected behaviour that is happening correct now after using ignoreNodes-

image

Thanks for your help. I’ll for now use this. Of course, this is not a workaround/solution but at least I don’t have to change my entire code for some kind of formatting workaround. Once this issue is solved, all I have to do is remove ignoreNodes and run eslint again.

But should we raise another bug for this?

when I write a new “type” expression inside a function, next lines take indent size from “type” expression:

function test(): void {
		type Test = 'test'; // 2 tabs, but needs 1 tab

		const test = 'test'; // also 2 tabs, because it takes from "type" expression
}

should be:

function test(): void {
	type Test = 'test'; // 1 tab

	const test = 'test'; // 1 tab
}

Those who come here would find it helpful to know a way to disable indentation checking for certain blocks of code. https://github.com/typescript-eslint/typescript-eslint/issues/455#issuecomment-580636221 StakOverflow

This is a pretty monster rule, and naturally quite important in the ecosystem. Sounds like a formidable but exciting challenge.

Those referencing issues are pretty useful for documenting some user-expected behavior; I found my specific complaint in #455.

At the risk of sounding foolish, @bradzacher, is there any other relevant work or notes you’ve uncovered in your research that might help for understanding this rule? (besides the linked PR #439)