简体   繁体   中英

alphabetically sort TypeScript interface keys

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;
}

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 .

在此处输入图像描述

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)

为了按字母顺序对对象键进行排序,我使用了扩展Sort JS Object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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