From c7154bf71cdceab97133898ac3347d2e6119eb3c Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Fri, 3 Jan 2025 18:40:58 +0000 Subject: [PATCH] chore(eslint-plugin): use `getConstraintInfo` in no-unnecessary-template-expression (#10578) Switches the `no-unnecessary-template-expression` rule to use `getConstraintInfo` internally. Related #10569 --- .../no-unnecessary-template-expression.ts | 22 +++++++++++++------ ...no-unnecessary-template-expression.test.ts | 5 +++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-template-expression.ts b/packages/eslint-plugin/src/rules/no-unnecessary-template-expression.ts index 90ad42fb0169..8556c51191dc 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-template-expression.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-template-expression.ts @@ -5,7 +5,7 @@ import * as ts from 'typescript'; import { createRule, - getConstrainedTypeAtLocation, + getConstraintInfo, getMovedNodeCode, getParserServices, isTypeFlagSet, @@ -51,21 +51,29 @@ export default createRule<[], MessageId>({ function isUnderlyingTypeString( expression: TSESTree.Expression, ): expression is TSESTree.Identifier | TSESTree.StringLiteral { - const type = getConstrainedTypeAtLocation(services, expression); + const checker = services.program.getTypeChecker(); + const { constraintType } = getConstraintInfo( + checker, + services.getTypeAtLocation(expression), + ); + + if (constraintType == null) { + return false; + } const isString = (t: ts.Type): boolean => { return isTypeFlagSet(t, ts.TypeFlags.StringLike); }; - if (type.isUnion()) { - return type.types.every(isString); + if (constraintType.isUnion()) { + return constraintType.types.every(isString); } - if (type.isIntersection()) { - return type.types.some(isString); + if (constraintType.isIntersection()) { + return constraintType.types.some(isString); } - return isString(type); + return isString(constraintType); } function isLiteral( diff --git a/packages/eslint-plugin/tests/rules/no-unnecessary-template-expression.test.ts b/packages/eslint-plugin/tests/rules/no-unnecessary-template-expression.test.ts index 6043b2b8b50d..eb87d7f3755d 100644 --- a/packages/eslint-plugin/tests/rules/no-unnecessary-template-expression.test.ts +++ b/packages/eslint-plugin/tests/rules/no-unnecessary-template-expression.test.ts @@ -1142,6 +1142,11 @@ this code has trailing whitespace: \${' '} // intentional comment after }\`; `, + ` + function getTpl(input: T) { + return \`\${input}\`; + } + `, ], invalid: [