Skip to content

Commit

Permalink
feat(eslint-plugin): add sort-interface-members rule
Browse files Browse the repository at this point in the history
  • Loading branch information
timkraut committed Feb 12, 2019
1 parent 61c60dc commit f501a7a
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 0 deletions.
53 changes: 53 additions & 0 deletions packages/eslint-plugin/src/rules/sort-interface-members.ts
@@ -0,0 +1,53 @@
/**
* @fileoverview Forbids unsorted interface members
*/

import { TSESTree } from '../../../typescript-estree/dist/parser';
import * as util from '../util';
import {
Identifier,
TSPropertySignature
} from '@typescript-eslint/typescript-estree/dist/ts-estree/ts-estree';

type Options = [];
type MessageIds = 'notSorted';

export default util.createRule<Options, MessageIds>({
name: 'sort-interface-members',
meta: {
type: 'suggestion',
docs: {
description: 'Forbids unsorted interface members',
category: 'Stylistic Issues',
recommended: false
},
schema: [],
messages: {
notSorted: 'The interface members are not sorted alphabetically.'
}
},
defaultOptions: [],
create(context) {
return {
TSInterfaceBody(node: TSESTree.TSInterfaceBody) {
const members = node.body as TSPropertySignature[];

for (let i = 0; i < members.length - 1; i++) {
const currentItemKey = members[i].key as Identifier;
const nextItemKey = members[i + 1].key as Identifier;

if (currentItemKey.name > nextItemKey.name) {
context.report({
messageId: 'notSorted',
node: currentItemKey
});

return; // Leave loop immediately
}
}

return; // No rule violation found
}
};
}
});
54 changes: 54 additions & 0 deletions packages/eslint-plugin/tests/rules/sort-interface-members.test.ts
@@ -0,0 +1,54 @@
import { RuleTester } from '../RuleTester';
import rule from '../../src/rules/sort-interface-members';

const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser'
});

ruleTester.run('sort-interface-members', rule, {
valid: [
`
interface Foo {
A: string;
B: string;
C: string;
}
`,
`
interface Foo {
A(): void;
B: string;
C: string;
}
`
],
invalid: [
{
code: `
interface Foo {
C: string;
B: string;
A: string;
}
`,
errors: [
{
messageId: 'notSorted'
}
]
},
{
code: `
interface Foo {
a: string;
A: string;
}
`,
errors: [
{
messageId: 'notSorted'
}
]
}
]
});

0 comments on commit f501a7a

Please sign in to comment.