alphabetically sort TypeScript interface keys

Viewed 6190

Is there a way to automatically sort TypeScript interface keys? I'm already using Prettier and VSCode so ideally the solution would be with those but I'm open to any solutions.

For example,

// before
interface MyInterface {
  foo: number;
  bar: number;
  baz: number;
}

// after sort
interface MyInterface {
  bar: number;
  baz: number;
  foo: number;
}
4 Answers

Lots of plugins are available for VSCode. "Sort" by "Henrik Sjööh" works nicely.

After installing the plugin, highlight the interface and press alt+shift+s (option+shift+s on MacOS) and the interface will be reordered.

In VS Code; you can simply select the lines you want to sort and then CMD + SHIFT + P (Ctrl + Shift + P on Windows) and search for Sort lines Ascending/Descending.

enter image description here

A perhaps better approach would be to enforce such a thing, especially if you are working on a team. Linters actually have support for this and it's called object-sort-keys for tslint and sort-keys for eslint. They also come with auto fixes within VS Code, so if you activate this rule on any linter, you can automatically fix the ordering of the keys. (You could even do this on Save -> fix all linting issues on save).

https://eslint.org/docs/rules/sort-keys

https://palantir.github.io/tslint/rules/object-literal-sort-keys/ (careful, tslint will be deprecated in favor of eslint soon)

To sort object keys alphabetically, I am using the extension Sort JS Object.

Related