### Install ESLint and TypeScript dependencies Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/README.md Installs the required dependencies for ESLint with TypeScript support. This includes eslint, typescript, and the TypeScript parser. Note that global installation requires global plugin installation as well. ```bash yarn add -D eslint typescript @typescript-eslint/parser ``` -------------------------------- ### Run ESLint CLI Commands for TypeScript Sorting Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Shows common npx eslint commands to check for sorting violations, apply automatic fixes, and customize output. Includes examples for checking all source files, fixing issues, using a custom config, directing results to a JSON report, and limiting the run to specific patterns. Requires the eslint-plugin-typescript-sort-keys plugin installed in the project. ```bash # Check files for sorting violations npx eslint --ext .ts,.tsx src/ # Auto-fix sorting violations npx eslint --ext .ts,.tsx src/ --fix # Check specific file npx eslint src/types/User.interface.ts # With custom config file npx eslint --config .eslintrc.custom.json src/ # Output results to file npx eslint src/ --output-file eslint-report.json --format json # Check and display only errors (ignore warnings) npx eslint src/ --quiet # Run on all TypeScript files in project npx eslint "**/*.ts" "**/*.tsx" --ignore-pattern "node_modules/" ``` -------------------------------- ### Install ESLint Plugin for TypeScript Sort Keys Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Installs the necessary ESLint dependencies and the typescript-sort-keys plugin using either yarn or npm. This is a prerequisite for using the plugin's features. ```bash # Install dependencies yarn add -D eslint typescript @typescript-eslint/parser yarn add -D eslint-plugin-typescript-sort-keys # Or with npm npm install --save-dev eslint typescript @typescript-eslint/parser npm install --save-dev eslint-plugin-typescript-sort-keys ``` -------------------------------- ### Example of Sorted vs Unsorted Interface Properties Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Demonstrates the correct and incorrect ways to define TypeScript interface properties according to the alphabetical sorting rule. The '✅ Correct' example shows properties sorted alphabetically, while the '❌ Incorrect' example shows them unsorted. ```typescript // ❌ Incorrect - properties not sorted interface User { age: number; name: string; email: string; } // ✅ Correct - properties sorted alphabetically interface User { age: number; email: string; name: string; } ``` -------------------------------- ### Install eslint-plugin-typescript-sort-keys Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/README.md Adds the TypeScript sort keys plugin as a development dependency. This plugin provides rules for sorting interface keys and string enum members. ```bash yarn add -D eslint-plugin-typescript-sort-keys ``` -------------------------------- ### Interface Rule: Descending Order Example Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Illustrates how to configure the 'interface' rule for descending alphabetical order. By setting the second argument to 'desc', properties will be sorted from Z to A. ```typescript // Descending order // .eslintrc.json: "desc" interface Settings { zIndex: number; width: number; height: number; } ``` -------------------------------- ### Configure Plugin with Recommended JSON Settings Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Provides JSON snippets for setting up the plugin in an ESLint configuration. Includes the basic recommended preset, a custom override for interface rule options, disabling a specific rule, and an example of per‑file overrides. These configurations can be placed in .eslintrc.json or other supported ESLint config formats. ```json { "extends": ["plugin:typescript-sort-keys/recommended"] } ``` ```json { "plugins": ["typescript-sort-keys"], "rules": { "typescript-sort-keys/interface": "error", "typescript-sort-keys/string-enum": "error" } } ``` ```json { "extends": ["plugin:typescript-sort-keys/recommended"], "rules": { "typescript-sort-keys/interface": [ "error", "asc", { "requiredFirst": true } ] } } ``` ```json { "extends": ["plugin:typescript-sort-keys/recommended"], "rules": { "typescript-sort-keys/string-enum": "off" } } ``` ```json { "extends": ["plugin:typescript-sort-keys/recommended"], "overrides": [ { "files": ["*.d.ts"], "rules": { "typescript-sort-keys/interface": "warn" } } ] } ``` -------------------------------- ### Interface Rule: Case-Insensitive Sorting Example Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Demonstrates case-insensitive sorting for interface properties. With 'caseSensitive: false', properties with different casing but the same base name are treated as equivalent for sorting purposes. ```typescript // With case-insensitive sorting // .eslintrc.json: "caseSensitive": false interface Config { apiKey: string; BaseUrl: string; // Treated as equal to 'baseUrl' debug: boolean; } ``` -------------------------------- ### Interface Rule: Required First Ordering Example Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Shows how the 'requiredFirst' option affects interface property ordering. When 'requiredFirst: true', all non-optional properties are listed before optional properties, maintaining a clear distinction. ```typescript // With requiredFirst enabled // .eslintrc.json: "requiredFirst": true interface Product { id: string; // Required properties first name: string; description?: string; // Optional properties after metadata?: object; } ``` -------------------------------- ### Interface Rule: Natural Sorting Example Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Illustrates the effect of enabling natural sorting for the 'interface' rule. With 'natural: true', numeric strings are sorted numerically (e.g., 'item1', 'item2', 'item10') instead of lexicographically. ```typescript // With natural sorting enabled // .eslintrc.json: "natural": true interface Items { item1: string; item2: string; item10: string; // Natural order: 1, 2, 10 (not 1, 10, 2) } ``` -------------------------------- ### String Enum Rule: Descending Order Example Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Illustrates configuring the 'string-enum' rule for descending order. By setting the order argument to 'desc', string enum members are sorted from Z to A. ```typescript // Descending order // .eslintrc.json: "desc" enum Direction { West = 'W', South = 'S', North = 'N', East = 'E', } ``` -------------------------------- ### String Enum Rule: Case-Insensitive Sorting Example Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Demonstrates case-insensitive sorting for string enum members. When 'caseSensitive: false' is configured, the 'Colors' enum shows members sorted without regard to their case. ```typescript // Case-insensitive sorting // .eslintrc.json: "caseSensitive": false enum Colors { blue = '#0000FF', Green = '#00FF00', red = '#FF0000', } ``` -------------------------------- ### Example of Sorted vs Unsorted String Enum Members Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Shows the correct and incorrect definitions of string enums based on alphabetical sorting. The '✅ Correct' enum has members sorted alphabetically, while the '❌ Incorrect' enum does not. ```typescript // ❌ Incorrect - enum members not sorted enum Status { Active = 'ACTIVE', Pending = 'PENDING', Inactive = 'INACTIVE', } // ✅ Correct - enum members sorted alphabetically enum Status { Active = 'ACTIVE', Inactive = 'INACTIVE', Pending = 'PENDING', } ``` -------------------------------- ### String Enum Rule: Excludes Numeric Enums Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Highlights that the 'string-enum' rule only applies to string enums. Numeric enums, regardless of their member order, will not trigger errors from this rule, as shown in the 'Priority' enum example. ```typescript // Only applies to string enums, not numeric enums enum Priority { High = 1, Low = 3, // No error - not a string enum Medium = 2, } ``` -------------------------------- ### Extend recommended typescript-sort-keys configuration Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/README.md Enables all recommended rules from the typescript-sort-keys plugin with default settings. This is a shorthand for enabling multiple rules at once. ```json { "extends": ["plugin:typescript-sort-keys/recommended"] } ``` -------------------------------- ### Create ESLint Rule with TypeScript Support Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Demonstrates the `createRule` utility function for creating ESLint rules with TypeScript support. It provides a structured approach including metadata, options, and a basic rule creation structure. It can utilize error messages and fixable code. ```typescript import { createRule, RuleMetaData } from './utils/rule'; import { SortingOrder, ErrorMessage } from './common/options'; // Define rule options type export type Options = [ 'asc' | 'desc', { caseSensitive?: boolean; natural?: boolean; } ]; // Define error messages const errorMessages = { invalidOrder: ErrorMessage.InterfaceInvalidOrder, } as const; // Define rule metadata const meta: RuleMetaData = { type: 'suggestion', docs: { description: 'require interface keys to be sorted', recommended: 'warn', }, messages: errorMessages, fixable: 'code', schema: [ { enum: ['asc', 'desc'], }, { type: 'object', properties: { caseSensitive: { type: 'boolean' }, natural: { type: 'boolean' }, }, additionalProperties: false, }, ], }; // Create the rule export const rule = createRule({ name: 'custom-rule', meta, defaultOptions: ['asc', { caseSensitive: true, natural: false }], create(context) { return { TSInterfaceDeclaration(node) { // Rule implementation const [order, options] = context.options; // Validation logic here }, }; }, }); ``` -------------------------------- ### Comparison Function Factory for Sorting Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Illustrates the usage of the `compareFn` factory function for creating comparison functions. The factory supports various options for case sensitivity and natural ordering of strings. ```typescript import { compareFn } from './utils/compare'; // Basic ascending comparison const ascendingCompare = compareFn(true, false, false); const result1 = ascendingCompare('apple', 'banana'); // -1 (apple < banana) const result2 = ascendingCompare('zebra', 'apple'); // 1 (zebra > apple) // Case-insensitive comparison const insensitiveCompare = compareFn(true, true, false); const result3 = insensitiveCompare('Apple', 'banana'); // -1 (treats as 'apple') const result4 = insensitiveCompare('ZEBRA', 'apple'); // 1 // Natural comparison for numeric strings const naturalCompare = compareFn(true, false, true); const result5 = naturalCompare('item1', 'item2'); // -1 const result6 = naturalCompare('item2', 'item10'); // -1 (2 < 10 naturally) const result7 = naturalCompare('item10', 'item2'); // 1 // Descending order const descendingCompare = compareFn(false, false, false); const result8 = descendingCompare('apple', 'banana'); // 1 (reversed) // Combined: case-insensitive + natural const combinedCompare = compareFn(true, true, true); const result9 = combinedCompare('Item2', 'item10'); // -1 // Usage in sorting arrays const keys = ['name', 'age', 'email', 'address']; keys.sort(compareFn(true, false, false)); // Result: ['address', 'age', 'email', 'name'] ``` -------------------------------- ### Create Reporter Function with TypeScript Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Demonstrates how to use the createReporter utility inside a custom ESLint rule to detect and auto‑fix ordering violations in interface and enum members. The snippet shows importing the reporter, configuring a custom error message, and invoking the reporter for interface bodies and type literals. It requires @typescript-eslint/experimental-utils and the plugin's utils. ```typescript import { createReporter } from './utils/plugin'; import { RuleContext } from '@typescript-eslint/experimental-utils/dist/ts-eslint'; // In a rule's create function export const rule = createRule({ name: 'interface', meta, defaultOptions: ['asc', { caseSensitive: true, natural: false }], create(context: RuleContext) { // Create a reporter with custom error message const compareNodeListAndReport = createReporter( context, ({ loc }) => ({ loc, messageId: 'invalidOrder', }) ); return { TSInterfaceDeclaration(node) { const body = node.body.body; // Report any ordering violations // This will automatically: // 1. Compare all properties using configured options // 2. Report errors for out-of-order properties // 3. Provide auto-fix that swaps nodes to correct order compareNodeListAndReport(body); }, TSTypeLiteral(node) { const body = node.members; compareNodeListAndReport(body); }, }; }, }); // The reporter handles: // - Parsing context options (asc/desc, caseSensitive, natural, requiredFirst) // - Comparing adjacent nodes // - Generating fix operations that preserve formatting and comments // - Handling punctuation (commas, semicolons) // - Maintaining indentation ``` -------------------------------- ### Configure TypeScript parser in ESLint config Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/README.md Sets the TypeScript parser in the ESLint configuration file. This is required for the plugin to properly parse TypeScript syntax. ```json { "parser": "@typescript-eslint/parser" } ``` -------------------------------- ### Configure Sort Order and Options for Interface Keys (TypeScript) Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/docs/rules/interface.md This snippet illustrates how to configure the 'typescript-sort-keys/interface' rule with custom options. It shows how to set descending order, enable natural sorting for numeric keys, and control case sensitivity and the placement of required properties. ```typescript /* eslint typescript-sort-keys/interface: ["error", "desc"] */ interface U { b: T c: T a: T } interface U { b: T c: T a: T } // Case-sensitive by default. interface U { C: T b: T a: T } // Non-required first order by default. interface U { a: T b?: T c: T } // Non-natural order by default. interface U { 10: T 2: T 1: T } ``` ```typescript /* eslint typescript-sort-keys/interface: ["error", "desc"] */ interface U { c: T b: T a: T } interface U { c: T b: T a: T } // Case-sensitive by default. interface U { b: T a: T C: T } // Non-required first order by default. interface U { c: T b?: T a: T } // Non-natural order by default. interface U { 2: T 10: T 1: T } ``` ```typescript /* eslint typescript-sort-keys/interface: ["error", "asc", { caseSensitive: false }] */ interface U { a: T c: T C: T b: T } interface U { a: T C: T c: T b: T } ``` ```typescript /* eslint typescript-sort-keys/interface: ["error", "asc", { caseSensitive: false }] */ interface U { a: T b: T c: T C: T } interface U { a: T b: T C: T c: T } ``` ```typescript /* eslint typescript-sort-keys/interface: ["error", "asc", { natural: true }] */ interface U { 1: T 10: T 2: T } ``` ```typescript /* eslint typescript-sort-keys/interface: ["error", "asc", { natural: true }] */ interface U { 1: T 2: T 10: T } ``` ```typescript /* eslint typescript-sort-keys/interface: ["error", "asc", { requiredFirst: true }] */ interface U { d: T c?: T b?: T a: T } ``` ```typescript /* eslint typescript-sort-keys/interface: ["error", "asc", { requiredFirst: true }] */ interface U { a: T d: T b?: T c?: T } ``` -------------------------------- ### Add typescript-sort-keys plugin to ESLint config Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/README.md Registers the typescript-sort-keys plugin in the ESLint configuration. The eslint-plugin- prefix can be omitted when specifying plugins. ```json { "plugins": ["typescript-sort-keys"] } ``` -------------------------------- ### Configure string-enum sorting rule (JSON) Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/docs/rules/string-enum.md Shows the JSON configuration required to enable the `string-enum` sorting rule in an ESLint configuration file. The options control sort direction (`asc` or `desc`), case sensitivity, and natural ordering. ```json {\n \"typescript-sort-keys/string-enum\": [\"error\", \"asc\", { \"caseSensitive\": true }]\n} ``` -------------------------------- ### Configure ESLint to Use TypeScript Sort Keys Plugin Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Configures ESLint to use the '@typescript-eslint/parser' and enables the 'typescript-sort-keys' plugin. It then specifies the 'interface' and 'string-enum' rules to be enforced with 'error' severity. ```json { "parser": "@typescript-eslint/parser", "plugins": ["typescript-sort-keys"], "rules": { "typescript-sort-keys/interface": "error", "typescript-sort-keys/string-enum": "error" } } ``` -------------------------------- ### Configure typescript-sort-keys rules Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/README.md Enables the interface and string-enum sorting rules as ESLint errors. Both rules are recommended for maintaining consistent code style in TypeScript projects. ```json { "rules": { "typescript-sort-keys/interface": "error", "typescript-sort-keys/string-enum": "error" } } ``` -------------------------------- ### Extract Property Name From TypeScript AST Nodes Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Demonstrates how to extract property names from various TypeScript AST nodes using the `getPropertyName` function, including interfaces, enums, and handles computed and numeric literals. ```typescript import { getPropertyName } from './utils/ast'; import { TSESTree } from '@typescript-eslint/experimental-utils'; // Example with interface properties const interfaceNode: TSESTree.TSInterfaceDeclaration = { type: 'TSInterfaceDeclaration', body: { body: [ { type: 'TSPropertySignature', key: { type: 'Identifier', name: 'username' } }, { type: 'TSPropertySignature', key: { type: 'Literal', value: 'email' } } ] } }; interfaceNode.body.body.forEach(member => { const name = getPropertyName(member); console.log(name); // 'username', 'email' }); // Example with enum members const enumNode: TSESTree.TSEnumDeclaration = { type: 'TSEnumDeclaration', members: [ { type: 'TSEnumMember', id: { type: 'Identifier', name: 'Active' } }, { type: 'TSEnumMember', id: { type: 'Literal', value: 'Pending' } } ] }; enumNode.members.forEach(member => { const name = getPropertyName(member); console.log(name); // 'Active', 'Pending' }); // Handles computed properties // For: interface Foo { ['computed']: string } // Returns: 'computed' // Handles numeric literals // For: interface Foo { 100: string } // Returns: '100' // Returns undefined for non-static names // For: interface Foo { [key: string]: any } // Returns: undefined (dynamic key) ``` -------------------------------- ### Configure Interface Rule for Sorted TypeScript Keys Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Configures the 'interface' rule for ESLint to enforce alphabetical sorting of TypeScript interface and type literal properties. Options include order ('asc'/'desc'), case sensitivity, natural sorting, and placing required properties first. Incorrectly sorted interfaces will trigger an error. ```json // .eslintrc.json { "rules": { "typescript-sort-keys/interface": [ "error", "asc", { "caseSensitive": true, "natural": false, "requiredFirst": false } ] } } ``` -------------------------------- ### String Enum Rule: Computed Property Names Support Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Shows that the 'string-enum' rule correctly handles string enums with computed property names, ensuring alphabetical sorting even when keys are dynamically generated. ```typescript // Computed property names are supported enum HttpMethod { 'delete' = 'DELETE', 'get' = 'GET', 'post' = 'POST', 'put' = 'PUT', } ``` -------------------------------- ### Enforce Sorted Interface Keys (TypeScript) Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/docs/rules/interface.md This snippet demonstrates the default behavior of the 'typescript-sort-keys/interface' rule, which enforces alphabetical sorting of interface property keys in ascending, case-sensitive order. It flags interfaces with unsorted keys as errors. ```typescript /* eslint typescript-sort-keys/interface: "error" */ interface U { a: T c: T b: T } interface U { a: T c: T b: T } // Case-sensitive by default. interface U { a: T b: T C: T } // Non-natural order by default. interface U { 1: T 2: T 10: T } // Non-required first order by default. interface U { b?: T a: T c: T } interface U { a: T ['c']: T b: T } ``` ```typescript /* eslint typescript-sort-keys/interface: "error" */ interface U { a: T b: T c: T } interface U { a: T b: T c: T } // Case-sensitive by default. interface U { C: T a: T b: T } // Non-natural order by default. interface U { 1: T 10: T 2: T } // Non-required first order by default. interface U { a: T b?: T c: T } // This rule checks computed properties which have a simple name as well. interface U { a: T ['b']: T c: T } ``` -------------------------------- ### Configure String Enum Rule for Sorted Members Source: https://context7.com/infctr/eslint-plugin-typescript-sort-keys/llms.txt Configures the 'string-enum' rule for ESLint to enforce alphabetical sorting of string enum members. Supports options like 'caseSensitive' and 'natural' sorting, similar to the 'interface' rule. ```json // .eslintrc.json { "rules": { "typescript-sort-keys/string-enum": [ "error", "asc", { "caseSensitive": true, "natural": false } ] } } ``` -------------------------------- ### Validate string enum members order (TypeScript) Source: https://github.com/infctr/eslint-plugin-typescript-sort-keys/blob/master/docs/rules/string-enum.md Demonstrates how the eslint rule `typescript-sort-keys/string-enum` flags incorrectly ordered string enum members and how correctly ordered members should look. The rule works on TypeScript enum declarations and can be applied in both ascending and descending modes. It does not modify code, only reports linting errors. ```typescript /* Incorrect ascending order */\nenum U {\n a = 'T',\n c = 'T',\n b = 'T',\n}\n\n/* Correct ascending order */\nenum U {\n a = 'T',\n b = 'T',\n c = 'T',\n}\n ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.