diff --git a/packages/eslint-plugin/src/rules/key-spacing.ts b/packages/eslint-plugin/src/rules/key-spacing.ts index 7bd325172983..fab4ced919ae 100644 --- a/packages/eslint-plugin/src/rules/key-spacing.ts +++ b/packages/eslint-plugin/src/rules/key-spacing.ts @@ -84,18 +84,9 @@ export default util.createRule({ /** * To handle index signatures, be able to get the end position of the parameters */ - function getKeyLocEnd( - node: - | TSESTree.TSIndexSignature - | TSESTree.TSPropertySignature - | TSESTree.PropertyDefinition, - ): TSESTree.Position { - if ('key' in node) { - return node.key.loc.end; - } - + function getKeyLocEnd(node: KeyTypeNode): TSESTree.Position { return getLastTokenBeforeColon( - node.parameters[node.parameters.length - 1], + 'key' in node ? node.key : node.parameters[node.parameters.length - 1], ).loc.end; } diff --git a/packages/eslint-plugin/tests/rules/key-spacing.test.ts b/packages/eslint-plugin/tests/rules/key-spacing.test.ts index 64e037b7336d..8911bce8d484 100644 --- a/packages/eslint-plugin/tests/rules/key-spacing.test.ts +++ b/packages/eslint-plugin/tests/rules/key-spacing.test.ts @@ -16,6 +16,10 @@ ruleTester.run('key-spacing', rule, { code: 'interface X {\n a: number;\n abc: string\n};', options: [{ align: 'value' }], }, + { + code: 'interface X {\n a?: number;\n abc: string\n};', + options: [{ align: 'value' }], + }, { code: 'interface X {\n a: number;\n // Some comment\n abc: string\n};', options: [{ align: 'value' }], @@ -36,6 +40,10 @@ ruleTester.run('key-spacing', rule, { code: 'class X {\n a: number;\n abc: string\n};', options: [{ align: 'value' }], }, + { + code: 'class X {\n a?: number;\n abc: string\n};', + options: [{ align: 'value' }], + }, { code: 'class X {\n a: number;\n\n abc: string\n};', options: [{ align: 'value' }],