While block indentation alignment (1) is enough for most people, I believe further alignment formatters, especially tabular or “vertical” alignment (2) tools, can greatly help in reducing the time it takes to visually process details in code:
// (1)
const bike: Record<string|number> = {
wheelSize: 16,
topTubeLength: 24.5,
manufacturer: 'Brompton'
};
// vs
// (2)
const bike: Record<string|number> = {
wheelSize: 16,
topTubeLength: 24.5,
manufacturer: 'Brompton'
};
The code in (2) is much clearer in tabular form.
Formatters
Every code-formatter out there can already do (1), e.g. prettier, js-beautifier. But very few can automatically align your object values vertically. Outside of using a built-in IDE code-formatting plugin, such as ones provided by IntelliJ IDEs (WebStorm, Android Studio), your options are limited on tools for this.
ESLint
I recently discovered that ESLint can actually do this in the same way that prettier does: automatically fix alignment.
It will also do this for Typescript files through a plugin @typescript-eslint/parser
!
As a proof of concept, you can create a file called notAligned.ts
that contains code from (1).
The formatting rule to use for this alignment is the key-spacing
and the CLI command to apply the alignment fixes directly is
eslint --fix --parser "@typescript-eslint/parser" --rule 'key-spacing: ["warn", {align: "value"} ]' --rule 'indent: ["warn"]' notAligned.ts
Once complete, you can peek inside notAligned.ts
to see that it should now look like (2).
This was quite the revelation for me!