From 83385ac351f45d3bcbd19f72711838e9a8473827 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sun, 8 Nov 2020 23:10:01 +0200 Subject: [PATCH] fix(eslint-plugin): [array-type] parenthesize ReadonlyArray fix (#2747) --- .../eslint-plugin/src/rules/array-type.ts | 19 ++++++++++--------- .../tests/rules/array-type.test.ts | 13 +++++++++++++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/packages/eslint-plugin/src/rules/array-type.ts b/packages/eslint-plugin/src/rules/array-type.ts index c77e2fa59fd..8c97729623a 100644 --- a/packages/eslint-plugin/src/rules/array-type.ts +++ b/packages/eslint-plugin/src/rules/array-type.ts @@ -244,7 +244,14 @@ export default util.createRule({ } const type = typeParams[0]; - const parens = typeNeedsParentheses(type); + const typeParens = typeNeedsParentheses(type); + const parentParens = + readonlyPrefix && node.parent?.type === AST_NODE_TYPES.TSArrayType; + + const start = `${parentParens ? '(' : ''}${readonlyPrefix}${ + typeParens ? '(' : '' + }`; + const end = `${typeParens ? ')' : ''}[]${parentParens ? ')' : ''}`; context.report({ node, @@ -254,14 +261,8 @@ export default util.createRule({ }, fix(fixer) { return [ - fixer.replaceTextRange( - [node.range[0], type.range[0]], - `${readonlyPrefix}${parens ? '(' : ''}`, - ), - fixer.replaceTextRange( - [type.range[1], node.range[1]], - parens ? ')[]' : '[]', - ), + fixer.replaceTextRange([node.range[0], type.range[0]], start), + fixer.replaceTextRange([type.range[1], node.range[1]], end), ]; }, }); diff --git a/packages/eslint-plugin/tests/rules/array-type.test.ts b/packages/eslint-plugin/tests/rules/array-type.test.ts index 73c1f517d68..6551bf6e7b9 100644 --- a/packages/eslint-plugin/tests/rules/array-type.test.ts +++ b/packages/eslint-plugin/tests/rules/array-type.test.ts @@ -1648,6 +1648,19 @@ interface FooInterface { }, ], }, + { + code: 'type Foo = ReadonlyArray[];', + output: 'type Foo = (readonly object[])[];', + options: [{ default: 'array' }], + errors: [ + { + messageId: 'errorStringArray', + data: { type: 'object' }, + line: 1, + column: 12, + }, + ], + }, ], });