From 8ec05bed0fed0dcd48b087acd5ab5a6132bf3b09 Mon Sep 17 00:00:00 2001 From: gtkatakura Date: Fri, 18 Mar 2022 15:26:22 -0300 Subject: [PATCH] fix(eslint-plugin): [consistent-type-assertions] enforce assertionStyle for `const` assertions (#4685) --- .../src/rules/consistent-type-assertions.ts | 6 +++--- .../rules/consistent-type-assertions.test.ts | 20 +++++++++++++------ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/eslint-plugin/src/rules/consistent-type-assertions.ts b/packages/eslint-plugin/src/rules/consistent-type-assertions.ts index 4a75edd7bda..c75b93eea0e 100644 --- a/packages/eslint-plugin/src/rules/consistent-type-assertions.ts +++ b/packages/eslint-plugin/src/rules/consistent-type-assertions.ts @@ -84,13 +84,13 @@ export default util.createRule({ function reportIncorrectAssertionType( node: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression, ): void { + const messageId = options.assertionStyle; + // If this node is `as const`, then don't report an error. - if (isConst(node.typeAnnotation)) { + if (isConst(node.typeAnnotation) && messageId === 'never') { return; } - const messageId = options.assertionStyle; - context.report({ node, messageId, diff --git a/packages/eslint-plugin/tests/rules/consistent-type-assertions.test.ts b/packages/eslint-plugin/tests/rules/consistent-type-assertions.test.ts index 1711e4450c3..a1d8e47645a 100644 --- a/packages/eslint-plugin/tests/rules/consistent-type-assertions.test.ts +++ b/packages/eslint-plugin/tests/rules/consistent-type-assertions.test.ts @@ -5,18 +5,26 @@ const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', }); -const ANGLE_BRACKET_TESTS = ` +const ANGLE_BRACKET_TESTS_EXCEPT_CONST_CASE = ` const x = new Generic(); const x = b; const x = [1]; -const x = ('string'); +const x = ('string');`; + +const ANGLE_BRACKET_TESTS = `${ANGLE_BRACKET_TESTS_EXCEPT_CONST_CASE} +const x = { key: 'value' }; `; -const AS_TESTS = ` + +const AS_TESTS_EXCEPT_CONST_CASE = ` const x = new Generic() as Foo; const x = b as A; const x = [1] as readonly number[]; -const x = ('string') as a | b; +const x = ('string') as a | b;`; + +const AS_TESTS = `${AS_TESTS_EXCEPT_CONST_CASE} +const x = { key: 'value' } as const; `; + const OBJECT_LITERAL_AS_CASTS = ` const x = {} as Foo; `; @@ -189,7 +197,7 @@ ruleTester.run('consistent-type-assertions', rule, { ], }), ...batchedSingleLineTests({ - code: AS_TESTS, + code: AS_TESTS_EXCEPT_CONST_CASE, options: [ { assertionStyle: 'never', @@ -219,7 +227,7 @@ ruleTester.run('consistent-type-assertions', rule, { ], }), ...batchedSingleLineTests({ - code: ANGLE_BRACKET_TESTS, + code: ANGLE_BRACKET_TESTS_EXCEPT_CONST_CASE, options: [ { assertionStyle: 'never',