简体   繁体   English

按字母顺序排序 TypeScript 接口键

[英]alphabetically sort TypeScript interface keys

Is there a way to automatically sort TypeScript interface keys?有没有办法自动排序TypeScript接口键? I'm already using Prettier and VSCode so ideally the solution would be with those but I'm open to any solutions.我已经在使用 Prettier 和 VSCode,所以理想情况下,解决方案应该是那些,但我对任何解决方案都持开放态度。

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. VSCode 有很多插件可用。 "Sort" by "Henrik Sjööh" works nicely. “Henrik Sjööh”的“排序”效果很好。

After installing the plugin, highlight the interface and press alt+shift+s ( option+shift+s on MacOS) and the interface will be reordered.安装插件后,突出显示界面并按alt+shift+s (在MacOS上为option+shift+s ),界面将重新排序。

In VS Code;在 VS 代码中; 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 .您可以简单地 select 要排序的行,然后CMD + SHIFT + P (在 Windows 上为Ctrl + Shift + P )并搜索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. Linter 实际上对此有支持,它被称为 tslint 的 object-sort-keys 和 eslint 的 sort-keys。 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.它们还带有 VS Code 中的自动修复功能,因此如果您在任何 linter 上激活此规则,您就可以自动修复键的顺序。 (You could even do this on Save -> fix all linting issues on save). (您甚至可以在保存时执行此操作 -> 在保存时修复所有 linting 问题)。

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) https://eslint.org/docs/rules/sort-keys https://palantir.github.io/tslint/rules/object-literal-sort-keys/ (小心,tslint 将很快被 eslint 弃用)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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