From ac502d83e857acc41a4e24e8d5297668ee3d821f Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Wed, 25 Oct 2023 11:12:35 +0300 Subject: [PATCH 1/2] chore(eslint-plugin): fixed no-unnecessary-condition complaints --- .../src/rules/adjacent-overload-signatures.ts | 54 ++++++------ .../eslint-plugin/src/rules/array-type.ts | 5 +- .../eslint-plugin/src/rules/block-spacing.ts | 1 - .../src/rules/class-methods-use-this.ts | 3 +- .../eslint-plugin/src/rules/comma-spacing.ts | 4 +- .../rules/consistent-generic-constructors.ts | 54 ++++++------ .../rules/consistent-indexed-object-style.ts | 12 +-- .../src/rules/consistent-type-assertions.ts | 7 +- .../src/rules/consistent-type-definitions.ts | 16 ++-- .../src/rules/consistent-type-exports.ts | 9 +- .../src/rules/consistent-type-imports.ts | 6 +- .../rules/explicit-function-return-type.ts | 3 +- .../rules/explicit-member-accessibility.ts | 2 +- .../rules/explicit-module-boundary-types.ts | 8 +- .../eslint-plugin/src/rules/key-spacing.ts | 20 ++--- .../src/rules/keyword-spacing.ts | 2 +- .../src/rules/lines-around-comment.ts | 12 ++- .../src/rules/member-delimiter-style.ts | 4 +- .../src/rules/member-ordering.ts | 8 +- .../src/rules/method-signature-style.ts | 4 +- .../naming-convention-utils/validator.ts | 2 +- .../src/rules/naming-convention.ts | 46 +++++----- .../rules/no-confusing-non-null-assertion.ts | 2 +- .../src/rules/no-empty-function.ts | 10 +-- .../src/rules/no-empty-interface.ts | 4 +- .../src/rules/no-explicit-any.ts | 3 +- .../src/rules/no-extra-parens.ts | 2 +- .../src/rules/no-floating-promises.ts | 5 +- .../src/rules/no-inferrable-types.ts | 13 +-- .../src/rules/no-invalid-void-type.ts | 6 +- .../eslint-plugin/src/rules/no-loop-func.ts | 2 +- .../src/rules/no-magic-numbers.ts | 4 +- .../src/rules/no-misused-promises.ts | 6 +- .../eslint-plugin/src/rules/no-mixed-enums.ts | 7 +- .../src/rules/no-non-null-assertion.ts | 4 +- .../eslint-plugin/src/rules/no-redeclare.ts | 2 +- .../rules/no-redundant-type-constituents.ts | 2 +- packages/eslint-plugin/src/rules/no-shadow.ts | 41 +++++---- .../no-unnecessary-boolean-literal-compare.ts | 3 +- .../src/rules/no-unnecessary-condition.ts | 5 +- .../rules/no-unnecessary-type-arguments.ts | 5 +- .../rules/no-unnecessary-type-assertion.ts | 2 +- .../src/rules/no-unsafe-argument.ts | 11 +-- .../src/rules/no-unsafe-assignment.ts | 3 +- .../eslint-plugin/src/rules/no-unused-vars.ts | 84 +++++++++---------- .../src/rules/no-use-before-define.ts | 13 +-- .../src/rules/no-useless-constructor.ts | 3 +- .../src/rules/no-var-requires.ts | 3 +- .../rules/padding-line-between-statements.ts | 16 ++-- .../eslint-plugin/src/rules/prefer-for-of.ts | 5 +- .../src/rules/prefer-function-type.ts | 2 +- .../src/rules/prefer-includes.ts | 2 +- .../src/rules/prefer-namespace-keyword.ts | 2 +- .../src/rules/prefer-nullish-coalescing.ts | 4 +- .../analyzeChain.ts | 2 +- .../src/rules/prefer-optional-chain.ts | 1 - .../src/rules/prefer-readonly.ts | 1 + .../src/rules/prefer-regexp-exec.ts | 7 +- .../src/rules/prefer-return-this-type.ts | 10 +-- .../rules/prefer-string-starts-ends-with.ts | 2 +- packages/eslint-plugin/src/rules/quotes.ts | 2 +- .../src/rules/require-array-sort-compare.ts | 3 +- .../eslint-plugin/src/rules/require-await.ts | 4 +- .../eslint-plugin/src/rules/return-await.ts | 6 +- .../src/rules/sort-type-constituents.ts | 2 +- .../src/rules/triple-slash-reference.ts | 2 +- .../src/rules/type-annotation-spacing.ts | 14 ++-- packages/eslint-plugin/src/rules/typedef.ts | 11 +-- .../eslint-plugin/src/rules/unbound-method.ts | 7 +- .../src/rules/unified-signatures.ts | 17 ++-- .../src/util/collectUnusedVariables.ts | 2 +- .../src/util/explicitReturnTypeUtils.ts | 23 ++--- .../eslint-plugin/src/util/getStringLength.ts | 2 +- .../src/util/getThisExpression.ts | 1 + packages/eslint-plugin/src/util/misc.ts | 2 +- .../tests/util/isNodeEqual.test.ts | 7 +- .../eslint-plugin/tools/generate-configs.ts | 2 +- 77 files changed, 301 insertions(+), 387 deletions(-) diff --git a/packages/eslint-plugin/src/rules/adjacent-overload-signatures.ts b/packages/eslint-plugin/src/rules/adjacent-overload-signatures.ts index 8af3cee44af2..32ef66ab9192 100644 --- a/packages/eslint-plugin/src/rules/adjacent-overload-signatures.ts +++ b/packages/eslint-plugin/src/rules/adjacent-overload-signatures.ts @@ -45,10 +45,6 @@ export default createRule({ * @returns the name and attribute of the member or null if it's a member not relevant to the rule. */ function getMemberMethod(member: TSESTree.Node): Method | null { - if (!member) { - return null; - } - const isStatic = 'static' in member && !!member.static; switch (member.type) { @@ -137,35 +133,33 @@ export default createRule({ function checkBodyForOverloadMethods(node: RuleNode): void { const members = getMembers(node); - if (members) { - let lastMethod: Method | null = null; - const seenMethods: Method[] = []; + let lastMethod: Method | null = null; + const seenMethods: Method[] = []; - members.forEach(member => { - const method = getMemberMethod(member); - if (method == null) { - lastMethod = null; - return; - } + members.forEach(member => { + const method = getMemberMethod(member); + if (method == null) { + lastMethod = null; + return; + } - const index = seenMethods.findIndex(seenMethod => - isSameMethod(method, seenMethod), - ); - if (index > -1 && !isSameMethod(method, lastMethod)) { - context.report({ - node: member, - messageId: 'adjacentSignature', - data: { - name: `${method.static ? 'static ' : ''}${method.name}`, - }, - }); - } else if (index === -1) { - seenMethods.push(method); - } + const index = seenMethods.findIndex(seenMethod => + isSameMethod(method, seenMethod), + ); + if (index > -1 && !isSameMethod(method, lastMethod)) { + context.report({ + node: member, + messageId: 'adjacentSignature', + data: { + name: `${method.static ? 'static ' : ''}${method.name}`, + }, + }); + } else if (index === -1) { + seenMethods.push(method); + } - lastMethod = method; - }); - } + lastMethod = method; + }); } return { diff --git a/packages/eslint-plugin/src/rules/array-type.ts b/packages/eslint-plugin/src/rules/array-type.ts index bc45356ae4ab..5f941665df21 100644 --- a/packages/eslint-plugin/src/rules/array-type.ts +++ b/packages/eslint-plugin/src/rules/array-type.ts @@ -28,7 +28,6 @@ function isSimpleType(node: TSESTree.Node): boolean { return true; case AST_NODE_TYPES.TSTypeReference: if ( - node.typeName && node.typeName.type === AST_NODE_TYPES.Identifier && node.typeName.name === 'Array' ) { @@ -144,7 +143,7 @@ export default createRule({ * @param node the node to be evaluated. */ function getMessageType(node: TSESTree.Node): string { - if (node && isSimpleType(node)) { + if (isSimpleType(node)) { return sourceCode.getText(node); } return 'T'; @@ -253,7 +252,7 @@ export default createRule({ const typeParens = typeNeedsParentheses(type); const parentParens = readonlyPrefix && - node.parent?.type === AST_NODE_TYPES.TSArrayType && + node.parent.type === AST_NODE_TYPES.TSArrayType && !isParenthesized(node.parent.elementType, sourceCode); const start = `${parentParens ? '(' : ''}${readonlyPrefix}${ diff --git a/packages/eslint-plugin/src/rules/block-spacing.ts b/packages/eslint-plugin/src/rules/block-spacing.ts index f66179002db9..93eabb54114e 100644 --- a/packages/eslint-plugin/src/rules/block-spacing.ts +++ b/packages/eslint-plugin/src/rules/block-spacing.ts @@ -83,7 +83,6 @@ export default createRule({ // Skip if the node is invalid or empty. if ( - openBrace.type !== AST_TOKEN_TYPES.Punctuator || openBrace.value !== '{' || closeBrace.type !== AST_TOKEN_TYPES.Punctuator || closeBrace.value !== '}' || diff --git a/packages/eslint-plugin/src/rules/class-methods-use-this.ts b/packages/eslint-plugin/src/rules/class-methods-use-this.ts index 3ed2667fe5a5..b3519db34e43 100644 --- a/packages/eslint-plugin/src/rules/class-methods-use-this.ts +++ b/packages/eslint-plugin/src/rules/class-methods-use-this.ts @@ -186,11 +186,10 @@ export default createRule({ const stackContext = popContext(); if ( stackContext?.member == null || - stackContext.class == null || stackContext.usesThis || (ignoreOverrideMethods && stackContext.member.override) || (ignoreClassesThatImplementAnInterface && - stackContext.class.implements != null) + stackContext.class.implements.length) ) { return; } diff --git a/packages/eslint-plugin/src/rules/comma-spacing.ts b/packages/eslint-plugin/src/rules/comma-spacing.ts index 9c6e64cfc5c8..b6549128960f 100644 --- a/packages/eslint-plugin/src/rules/comma-spacing.ts +++ b/packages/eslint-plugin/src/rules/comma-spacing.ts @@ -183,7 +183,7 @@ export default createRule({ } const prevToken = tokensAndComments[i - 1]; - const nextToken = tokensAndComments[i + 1]; + const nextToken = tokensAndComments.at(i + 1); validateCommaSpacing( token, @@ -192,7 +192,7 @@ export default createRule({ : prevToken, (nextToken && isCommaToken(nextToken)) || ignoredTokens.has(token) ? null - : nextToken, + : nextToken ?? null, ); }); }, diff --git a/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts b/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts index 8719d0b5dc5d..10026c278293 100644 --- a/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts +++ b/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts @@ -108,37 +108,35 @@ export default createRule({ } return; } - if (mode === 'constructor') { - if (lhs?.typeArguments && !rhs.typeArguments) { - const hasParens = - sourceCode.getTokenAfter(rhs.callee)?.value === '('; - const extraComments = new Set( - sourceCode.getCommentsInside(lhs.parent), - ); - sourceCode - .getCommentsInside(lhs.typeArguments) - .forEach(c => extraComments.delete(c)); - context.report({ - node, - messageId: 'preferConstructor', - *fix(fixer) { - yield fixer.remove(lhs.parent); - for (const comment of extraComments) { - yield fixer.insertTextAfter( - rhs.callee, - sourceCode.getText(comment), - ); - } + + if (lhs?.typeArguments && !rhs.typeArguments) { + const hasParens = sourceCode.getTokenAfter(rhs.callee)?.value === '('; + const extraComments = new Set( + sourceCode.getCommentsInside(lhs.parent), + ); + sourceCode + .getCommentsInside(lhs.typeArguments) + .forEach(c => extraComments.delete(c)); + context.report({ + node, + messageId: 'preferConstructor', + *fix(fixer) { + yield fixer.remove(lhs.parent); + for (const comment of extraComments) { yield fixer.insertTextAfter( rhs.callee, - sourceCode.getText(lhs.typeArguments), + sourceCode.getText(comment), ); - if (!hasParens) { - yield fixer.insertTextAfter(rhs.callee, '()'); - } - }, - }); - } + } + yield fixer.insertTextAfter( + rhs.callee, + sourceCode.getText(lhs.typeArguments), + ); + if (!hasParens) { + yield fixer.insertTextAfter(rhs.callee, '()'); + } + }, + }); } }, }; diff --git a/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts b/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts index 5aece3ea4802..31ffd08e30e6 100644 --- a/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts +++ b/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts @@ -47,15 +47,11 @@ export default createRule({ return; } - const [parameter] = member.parameters; - - if (!parameter) { + const parameter = member.parameters.at(0); + if (parameter?.type !== AST_NODE_TYPES.Identifier) { return; } - if (parameter.type !== AST_NODE_TYPES.Identifier) { - return; - } const keyType = parameter.typeAnnotation; if (!keyType) { return; @@ -133,7 +129,7 @@ export default createRule({ TSInterfaceDeclaration(node): void { let genericTypes = ''; - if (node.typeParameters?.params?.length) { + if (node.typeParameters?.params.length) { genericTypes = `<${node.typeParameters.params .map(p => sourceCode.getText(p)) .join(', ')}>`; @@ -145,7 +141,7 @@ export default createRule({ node.id, `type ${node.id.name}${genericTypes} = `, ';', - !node.extends?.length, + !node.extends.length, ); }, }), diff --git a/packages/eslint-plugin/src/rules/consistent-type-assertions.ts b/packages/eslint-plugin/src/rules/consistent-type-assertions.ts index 0c3883f81809..a5fd18a7c836 100644 --- a/packages/eslint-plugin/src/rules/consistent-type-assertions.ts +++ b/packages/eslint-plugin/src/rules/consistent-type-assertions.ts @@ -225,13 +225,10 @@ export default createRule({ return; } - if ( - checkType(node.typeAnnotation) && - node.expression.type === AST_NODE_TYPES.ObjectExpression - ) { + if (checkType(node.typeAnnotation)) { const suggest: TSESLint.ReportSuggestionArray = []; if ( - node.parent?.type === AST_NODE_TYPES.VariableDeclarator && + node.parent.type === AST_NODE_TYPES.VariableDeclarator && !node.parent.id.typeAnnotation ) { const { parent } = node; diff --git a/packages/eslint-plugin/src/rules/consistent-type-definitions.ts b/packages/eslint-plugin/src/rules/consistent-type-definitions.ts index 2a9acedd14a5..ebd902c4f7a9 100644 --- a/packages/eslint-plugin/src/rules/consistent-type-definitions.ts +++ b/packages/eslint-plugin/src/rules/consistent-type-definitions.ts @@ -99,17 +99,15 @@ export default createRule({ ); } - if (node.extends) { - node.extends.forEach(heritage => { - const typeIdentifier = sourceCode.getText(heritage); - fixes.push( - fixer.insertTextAfter(node.body, ` & ${typeIdentifier}`), - ); - }); - } + node.extends.forEach(heritage => { + const typeIdentifier = sourceCode.getText(heritage); + fixes.push( + fixer.insertTextAfter(node.body, ` & ${typeIdentifier}`), + ); + }); if ( - node.parent?.type === AST_NODE_TYPES.ExportDefaultDeclaration + node.parent.type === AST_NODE_TYPES.ExportDefaultDeclaration ) { fixes.push( fixer.removeRange([node.parent.range[0], node.range[0]]), diff --git a/packages/eslint-plugin/src/rules/consistent-type-exports.ts b/packages/eslint-plugin/src/rules/consistent-type-exports.ts index 36e27f91d73a..450fbe103d4a 100644 --- a/packages/eslint-plugin/src/rules/consistent-type-exports.ts +++ b/packages/eslint-plugin/src/rules/consistent-type-exports.ts @@ -90,10 +90,14 @@ export default createRule({ ): boolean | undefined { const checker = services.program.getTypeChecker(); const symbol = services.getSymbolAtLocation(specifier.exported); - const aliasedSymbol = checker.getAliasedSymbol(symbol!); + if (!symbol) { + return undefined; + } + + const aliasedSymbol = checker.getAliasedSymbol(symbol); // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison - if (!aliasedSymbol || aliasedSymbol.escapedName === 'unknown') { + if (aliasedSymbol.escapedName === 'unknown') { return undefined; } @@ -104,6 +108,7 @@ export default createRule({ ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration): void { // Coerce the source into a string for use as a lookup entry. const source = getSourceFromExport(node) ?? 'undefined'; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const sourceExports = (sourceExportsMap[source] ||= { source, reportValueExports: [], diff --git a/packages/eslint-plugin/src/rules/consistent-type-imports.ts b/packages/eslint-plugin/src/rules/consistent-type-imports.ts index 57e15ea29174..8c821f960882 100644 --- a/packages/eslint-plugin/src/rules/consistent-type-imports.ts +++ b/packages/eslint-plugin/src/rules/consistent-type-imports.ts @@ -115,6 +115,7 @@ export default createRule({ ImportDeclaration(node): void { const source = node.source.value; // sourceImports is the object containing all the specifics for a particular import source, type or value + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition sourceImportsMap[source] ??= { source, reportValueImports: [], // if there is a mismatch where type importKind but value specifiers @@ -180,9 +181,9 @@ export default createRule({ * export default Type; */ if ( - ref.identifier.parent?.type === + ref.identifier.parent.type === AST_NODE_TYPES.ExportSpecifier || - ref.identifier.parent?.type === + ref.identifier.parent.type === AST_NODE_TYPES.ExportDefaultDeclaration ) { if (ref.isValueReference && ref.isTypeReference) { @@ -193,6 +194,7 @@ export default createRule({ let parent: TSESTree.Node | undefined = ref.identifier.parent; let child: TSESTree.Node = ref.identifier; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (parent) { switch (parent.type) { // CASE 1: diff --git a/packages/eslint-plugin/src/rules/explicit-function-return-type.ts b/packages/eslint-plugin/src/rules/explicit-function-return-type.ts index e72079c064b8..0091647a78c3 100644 --- a/packages/eslint-plugin/src/rules/explicit-function-return-type.ts +++ b/packages/eslint-plugin/src/rules/explicit-function-return-type.ts @@ -125,7 +125,7 @@ export default createRule({ let funcName; if (node.id?.name) { funcName = node.id.name; - } else if (parent) { + } else { switch (parent.type) { case AST_NODE_TYPES.VariableDeclarator: { if (parent.id.type === AST_NODE_TYPES.Identifier) { @@ -153,7 +153,6 @@ export default createRule({ if ( node.type === AST_NODE_TYPES.FunctionDeclaration && node.id && - node.id.type === AST_NODE_TYPES.Identifier && !!options.allowedNames.includes(node.id.name) ) { return true; diff --git a/packages/eslint-plugin/src/rules/explicit-member-accessibility.ts b/packages/eslint-plugin/src/rules/explicit-member-accessibility.ts index ff99eb77b4a8..9cb7133cdc11 100644 --- a/packages/eslint-plugin/src/rules/explicit-member-accessibility.ts +++ b/packages/eslint-plugin/src/rules/explicit-member-accessibility.ts @@ -227,7 +227,7 @@ export default createRule({ accessibility: TSESTree.Accessibility, fixer: TSESLint.RuleFixer, ): TSESLint.RuleFix | null { - if (node?.decorators.length) { + if (node.decorators.length) { const lastDecorator = node.decorators[node.decorators.length - 1]; const nextToken = sourceCode.getTokenAfter(lastDecorator)!; return fixer.insertTextBefore(nextToken, `${accessibility} `); diff --git a/packages/eslint-plugin/src/rules/explicit-module-boundary-types.ts b/packages/eslint-plugin/src/rules/explicit-module-boundary-types.ts index d2cb5f5306f8..a2aa7c6be143 100644 --- a/packages/eslint-plugin/src/rules/explicit-module-boundary-types.ts +++ b/packages/eslint-plugin/src/rules/explicit-module-boundary-types.ts @@ -272,7 +272,7 @@ export default createRule({ while (current) { if (current.type === AST_NODE_TYPES.ReturnStatement) { // the parent of a return will always be a block statement, so we can skip over it - current = current.parent?.parent; + current = current.parent.parent; continue; } @@ -405,11 +405,11 @@ export default createRule({ node: TSESTree.TSEmptyBodyFunctionExpression, ): void { const isConstructor = - node.parent?.type === AST_NODE_TYPES.MethodDefinition && + node.parent.type === AST_NODE_TYPES.MethodDefinition && node.parent.kind === 'constructor'; const isSetAccessor = - (node.parent?.type === AST_NODE_TYPES.TSAbstractMethodDefinition || - node.parent?.type === AST_NODE_TYPES.MethodDefinition) && + (node.parent.type === AST_NODE_TYPES.TSAbstractMethodDefinition || + node.parent.type === AST_NODE_TYPES.MethodDefinition) && node.parent.kind === 'set'; if (!isConstructor && !isSetAccessor && !node.returnType) { context.report({ diff --git a/packages/eslint-plugin/src/rules/key-spacing.ts b/packages/eslint-plugin/src/rules/key-spacing.ts index 707c9dc4431b..066226389612 100644 --- a/packages/eslint-plugin/src/rules/key-spacing.ts +++ b/packages/eslint-plugin/src/rules/key-spacing.ts @@ -23,16 +23,6 @@ const baseSchema = Array.isArray(baseRule.meta.schema) ? baseRule.meta.schema[0] : baseRule.meta.schema; -/** - * TODO: replace with native .at() once Node 14 stops being supported - */ -function at(arr: T[], position: number): T | undefined { - if (position < 0) { - return arr[arr.length + position]; - } - return arr[position]; -} - export default createRule({ name: 'key-spacing', meta: { @@ -59,7 +49,7 @@ export default createRule({ function adjustedColumn(position: TSESTree.Position): number { const line = position.line - 1; // position.line is 1-indexed return getStringLength( - at(sourceCode.lines, line)!.slice(0, position.column), + sourceCode.lines.at(line)!.slice(0, position.column), ); } @@ -114,7 +104,7 @@ export default createRule({ return code.slice( 0, sourceCode.getTokenAfter( - at(node.parameters, -1)!, + node.parameters.at(-1)!, isClosingBracketToken, )!.range[1] - node.range[0], ); @@ -129,7 +119,7 @@ export default createRule({ return getLastTokenBeforeColon( node.type !== AST_NODE_TYPES.TSIndexSignature ? node.key - : at(node.parameters, -1)!, + : node.parameters.at(-1)!, ).loc.end; } @@ -230,7 +220,7 @@ export default createRule({ if ( leadingComments.length && leadingComments[0].loc.start.line - groupEndLine <= 1 && - candidateValueStartLine - at(leadingComments, -1)!.loc.end.line <= 1 + candidateValueStartLine - leadingComments.at(-1)!.loc.end.line <= 1 ) { for (let i = 1; i < leadingComments.length; i++) { if ( @@ -400,7 +390,7 @@ export default createRule({ let prevNode: TSESTree.Node | undefined = undefined; for (const node of members) { - let prevAlignedNode = at(currentAlignGroup, -1); + let prevAlignedNode = currentAlignGroup.at(-1); if (prevAlignedNode !== prevNode) { prevAlignedNode = undefined; } diff --git a/packages/eslint-plugin/src/rules/keyword-spacing.ts b/packages/eslint-plugin/src/rules/keyword-spacing.ts index 50fbdc18d22b..2b30eff28396 100644 --- a/packages/eslint-plugin/src/rules/keyword-spacing.ts +++ b/packages/eslint-plugin/src/rules/keyword-spacing.ts @@ -81,7 +81,7 @@ export default createRule({ const typeToken = sourceCode.getFirstToken(node, { skip: 1 })!; const punctuatorToken = sourceCode.getTokenAfter(typeToken)!; if ( - node.specifiers?.[0]?.type === AST_NODE_TYPES.ImportDefaultSpecifier + node.specifiers[0]?.type === AST_NODE_TYPES.ImportDefaultSpecifier ) { return; } diff --git a/packages/eslint-plugin/src/rules/lines-around-comment.ts b/packages/eslint-plugin/src/rules/lines-around-comment.ts index 1855c8ae5b8c..1e740ae4327d 100644 --- a/packages/eslint-plugin/src/rules/lines-around-comment.ts +++ b/packages/eslint-plugin/src/rules/lines-around-comment.ts @@ -441,13 +441,11 @@ export default createRule({ before: options.beforeLineComment, }); } - } else if (token.type === AST_TOKEN_TYPES.Block) { - if (options.beforeBlockComment || options.afterBlockComment) { - checkForEmptyLine(token, { - after: options.afterBlockComment, - before: options.beforeBlockComment, - }); - } + } else if (options.beforeBlockComment || options.afterBlockComment) { + checkForEmptyLine(token, { + after: options.afterBlockComment, + before: options.beforeBlockComment, + }); } }); }, diff --git a/packages/eslint-plugin/src/rules/member-delimiter-style.ts b/packages/eslint-plugin/src/rules/member-delimiter-style.ts index 2a0880cd21fb..db6c3673f146 100644 --- a/packages/eslint-plugin/src/rules/member-delimiter-style.ts +++ b/packages/eslint-plugin/src/rules/member-delimiter-style.ts @@ -252,7 +252,7 @@ export default createRule({ .pop(); const sourceCodeLines = sourceCode.getLines(); - const lastTokenLine = sourceCodeLines[lastToken?.loc.start.line - 1]; + const lastTokenLine = sourceCodeLines[lastToken.loc.start.line - 1]; const optsSemi = getOption('semi'); const optsComma = getOption('comma'); @@ -340,7 +340,7 @@ export default createRule({ : { ...typeOpts.multiline, type: 'multi-line' }; members.forEach((member, index) => { - checkLastToken(member, opts ?? {}, index === members.length - 1); + checkLastToken(member, opts, index === members.length - 1); }); } diff --git a/packages/eslint-plugin/src/rules/member-ordering.ts b/packages/eslint-plugin/src/rules/member-ordering.ts index 84d34d4c596c..aeda6785f4cf 100644 --- a/packages/eslint-plugin/src/rules/member-ordering.ts +++ b/packages/eslint-plugin/src/rules/member-ordering.ts @@ -485,7 +485,7 @@ function getAccessibility(node: Member): Accessibility { if ('accessibility' in node && node.accessibility) { return node.accessibility; } - if ('key' in node && node.key?.type === AST_NODE_TYPES.PrivateIdentifier) { + if ('key' in node && node.key.type === AST_NODE_TYPES.PrivateIdentifier) { return '#private'; } return 'public'; @@ -725,13 +725,13 @@ export default createRule({ let isCorrectlySorted = true; // Find first member which isn't correctly sorted - members.forEach(member => { + for (const member of members) { const rank = getRank(member, groupOrder, supportsModifiers); const name = getMemberName(member, context.getSourceCode()); const rankLastMember = previousRanks[previousRanks.length - 1]; if (rank === -1) { - return; + continue; } // Works for 1st item because x < undefined === false for any x (typeof string) @@ -754,7 +754,7 @@ export default createRule({ previousRanks.push(rank); memberGroups.push([member]); } - }); + } return isCorrectlySorted ? memberGroups : null; } diff --git a/packages/eslint-plugin/src/rules/method-signature-style.ts b/packages/eslint-plugin/src/rules/method-signature-style.ts index 20a56b54ecbe..8168f0cea04e 100644 --- a/packages/eslint-plugin/src/rules/method-signature-style.ts +++ b/packages/eslint-plugin/src/rules/method-signature-style.ts @@ -130,9 +130,9 @@ export default createRule({ const parent = methodNode.parent; const members = - parent?.type === AST_NODE_TYPES.TSInterfaceBody + parent.type === AST_NODE_TYPES.TSInterfaceBody ? parent.body - : parent?.type === AST_NODE_TYPES.TSTypeLiteral + : parent.type === AST_NODE_TYPES.TSTypeLiteral ? parent.members : []; diff --git a/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts b/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts index d7ce337b1a11..a21ba7b9844e 100644 --- a/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts +++ b/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts @@ -167,7 +167,7 @@ function createValidator( count, affixes: affixes?.join(', '), formats: formats?.map(f => PredefinedFormats[f]).join(', '), - regex: custom?.regex?.toString(), + regex: custom?.regex.toString(), regexMatch: custom?.match === true ? 'match' diff --git a/packages/eslint-plugin/src/rules/naming-convention.ts b/packages/eslint-plugin/src/rules/naming-convention.ts index 15bb22b955cc..0b76d1398192 100644 --- a/packages/eslint-plugin/src/rules/naming-convention.ts +++ b/packages/eslint-plugin/src/rules/naming-convention.ts @@ -81,7 +81,6 @@ export default createRule({ defaultOptions: defaultCamelCaseAllTheThingsConfig, create(contextWithoutDefaults) { const context = - contextWithoutDefaults.options && contextWithoutDefaults.options.length > 0 ? contextWithoutDefaults : // only apply the defaults when the user provides no config @@ -108,10 +107,6 @@ export default createRule({ | TSESTree.TSPropertySignatureNonComputedName, modifiers: Set, ): void { - if (!validator) { - return; - } - const key = node.key; if (requiresQuoting(key, compilerOptions.target)) { modifiers.add(Modifiers.requiresQuotes); @@ -180,11 +175,11 @@ export default createRule({ return ( // `const { x }` // does not match `const { x: y }` - (id.parent?.type === AST_NODE_TYPES.Property && id.parent.shorthand) || + (id.parent.type === AST_NODE_TYPES.Property && id.parent.shorthand) || // `const { x = 2 }` // does not match const `{ x: y = 2 }` - (id.parent?.type === AST_NODE_TYPES.AssignmentPattern && - id.parent.parent?.type === AST_NODE_TYPES.Property && + (id.parent.type === AST_NODE_TYPES.AssignmentPattern && + id.parent.parent.type === AST_NODE_TYPES.Property && id.parent.parent.shorthand) ); } @@ -208,12 +203,11 @@ export default createRule({ function isAsyncVariableIdentifier(id: TSESTree.Identifier): boolean { return Boolean( - id.parent && - (('async' in id.parent && id.parent.async) || - ('init' in id.parent && - id.parent.init && - 'async' in id.parent.init && - id.parent.init.async)), + ('async' in id.parent && id.parent.async) || + ('init' in id.parent && + id.parent.init && + 'async' in id.parent.init && + id.parent.init.async), ); } @@ -270,7 +264,7 @@ export default createRule({ const baseModifiers = new Set(); const parent = node.parent; - if (parent?.type === AST_NODE_TYPES.VariableDeclaration) { + if (parent.type === AST_NODE_TYPES.VariableDeclaration) { if (parent.kind === 'const') { baseModifiers.add(Modifiers.const); } @@ -684,16 +678,14 @@ export default createRule({ }; return Object.fromEntries( - Object.entries(selectors) - .map(([selector, { validator, handler }]) => { - return [ - selector, - (node: Parameters[0]): void => { - handler(node, validator); - }, - ] as const; - }) - .filter((s): s is NonNullable => s != null), + Object.entries(selectors).map(([selector, { validator, handler }]) => { + return [ + selector, + (node: Parameters[0]): void => { + handler(node, validator); + }, + ] as const; + }), ); }, }); @@ -728,8 +720,8 @@ function isExported( for (const ref of variable.references) { const refParent = ref.identifier.parent; if ( - refParent?.type === AST_NODE_TYPES.ExportDefaultDeclaration || - refParent?.type === AST_NODE_TYPES.ExportSpecifier + refParent.type === AST_NODE_TYPES.ExportDefaultDeclaration || + refParent.type === AST_NODE_TYPES.ExportSpecifier ) { return true; } diff --git a/packages/eslint-plugin/src/rules/no-confusing-non-null-assertion.ts b/packages/eslint-plugin/src/rules/no-confusing-non-null-assertion.ts index 7b42603f2ba6..165ee127f3a7 100644 --- a/packages/eslint-plugin/src/rules/no-confusing-non-null-assertion.ts +++ b/packages/eslint-plugin/src/rules/no-confusing-non-null-assertion.ts @@ -50,7 +50,7 @@ export default createRule({ const tokenAfterLeft = sourceCode.getTokenAfter(node.left); if ( leftHandFinalToken?.type === AST_TOKEN_TYPES.Punctuator && - leftHandFinalToken?.value === '!' && + leftHandFinalToken.value === '!' && tokenAfterLeft?.value !== ')' ) { if (isLeftHandPrimaryExpression(node.left)) { diff --git a/packages/eslint-plugin/src/rules/no-empty-function.ts b/packages/eslint-plugin/src/rules/no-empty-function.ts index f7189d6dacb1..6a8e90ebaf13 100644 --- a/packages/eslint-plugin/src/rules/no-empty-function.ts +++ b/packages/eslint-plugin/src/rules/no-empty-function.ts @@ -83,7 +83,7 @@ export default createRule({ function isBodyEmpty( node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression, ): boolean { - return !node.body || node.body.body.length === 0; + return node.body.body.length === 0; } /** @@ -95,7 +95,7 @@ export default createRule({ function hasParameterProperties( node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression, ): boolean { - return node.params?.some( + return node.params.some( param => param.type === AST_NODE_TYPES.TSParameterProperty, ); } @@ -111,7 +111,7 @@ export default createRule({ const parent = node.parent; if ( isBodyEmpty(node) && - parent?.type === AST_NODE_TYPES.MethodDefinition && + parent.type === AST_NODE_TYPES.MethodDefinition && parent.kind === 'constructor' ) { const { accessibility } = parent; @@ -139,7 +139,7 @@ export default createRule({ ): boolean { if (isAllowedDecoratedFunctions && isBodyEmpty(node)) { const decorators = - node.parent?.type === AST_NODE_TYPES.MethodDefinition + node.parent.type === AST_NODE_TYPES.MethodDefinition ? node.parent.decorators : undefined; return !!decorators && !!decorators.length; @@ -154,7 +154,7 @@ export default createRule({ return ( isAllowedOverrideMethods && isBodyEmpty(node) && - node.parent?.type === AST_NODE_TYPES.MethodDefinition && + node.parent.type === AST_NODE_TYPES.MethodDefinition && node.parent.override ); } diff --git a/packages/eslint-plugin/src/rules/no-empty-interface.ts b/packages/eslint-plugin/src/rules/no-empty-interface.ts index 2ca3a27fdf28..bffb85d197ef 100644 --- a/packages/eslint-plugin/src/rules/no-empty-interface.ts +++ b/packages/eslint-plugin/src/rules/no-empty-interface.ts @@ -55,7 +55,7 @@ export default createRule({ } const extend = node.extends; - if (!extend || extend.length === 0) { + if (extend.length === 0) { context.report({ node: node.id, messageId: 'noEmpty', @@ -79,7 +79,7 @@ export default createRule({ const mergedWithClassDeclaration = scope.set .get(node.id.name) - ?.defs?.some( + ?.defs.some( def => def.node.type === AST_NODE_TYPES.ClassDeclaration, ); diff --git a/packages/eslint-plugin/src/rules/no-explicit-any.ts b/packages/eslint-plugin/src/rules/no-explicit-any.ts index ccf4cf47fb0f..923750847365 100644 --- a/packages/eslint-plugin/src/rules/no-explicit-any.ts +++ b/packages/eslint-plugin/src/rules/no-explicit-any.ts @@ -109,7 +109,6 @@ export default createRule({ function isNodeValidArrayTSTypeReference(node: TSESTree.Node): boolean { return ( node.type === AST_NODE_TYPES.TSTypeReference && - node.typeName !== undefined && node.typeName.type === AST_NODE_TYPES.Identifier && ['Array', 'ReadonlyArray'].includes(node.typeName.name) ); @@ -136,7 +135,7 @@ export default createRule({ */ function isGreatGrandparentRestElement(node: TSESTree.Node): boolean { return ( - node?.parent?.parent?.parent != null && + node.parent?.parent?.parent != null && isNodeRestElementInFunction(node.parent.parent.parent) ); } diff --git a/packages/eslint-plugin/src/rules/no-extra-parens.ts b/packages/eslint-plugin/src/rules/no-extra-parens.ts index ab708faa83db..180bc4a0b973 100644 --- a/packages/eslint-plugin/src/rules/no-extra-parens.ts +++ b/packages/eslint-plugin/src/rules/no-extra-parens.ts @@ -1,5 +1,5 @@ // any is required to work around manipulating the AST in weird ways -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-unsafe-assignment */ import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; import { AST_NODE_TYPES } from '@typescript-eslint/utils'; diff --git a/packages/eslint-plugin/src/rules/no-floating-promises.ts b/packages/eslint-plugin/src/rules/no-floating-promises.ts index 066469c3507d..9c1e9f785c18 100644 --- a/packages/eslint-plugin/src/rules/no-floating-promises.ts +++ b/packages/eslint-plugin/src/rules/no-floating-promises.ts @@ -185,10 +185,9 @@ export default createRule({ } return ( - node.expression.type === AST_NODE_TYPES.CallExpression && - (node.expression.callee.type === + node.expression.callee.type === AST_NODE_TYPES.ArrowFunctionExpression || - node.expression.callee.type === AST_NODE_TYPES.FunctionExpression) + node.expression.callee.type === AST_NODE_TYPES.FunctionExpression ); } diff --git a/packages/eslint-plugin/src/rules/no-inferrable-types.ts b/packages/eslint-plugin/src/rules/no-inferrable-types.ts index 15f88ca85c07..606a3d8cffc5 100644 --- a/packages/eslint-plugin/src/rules/no-inferrable-types.ts +++ b/packages/eslint-plugin/src/rules/no-inferrable-types.ts @@ -199,7 +199,7 @@ export default createRule({ typeNode: TSESTree.TSTypeAnnotation | undefined, initNode: TSESTree.Expression | null | undefined, ): void { - if (!typeNode || !initNode || !typeNode.typeAnnotation) { + if (!typeNode || !initNode) { return; } @@ -235,9 +235,6 @@ export default createRule({ function inferrableVariableVisitor( node: TSESTree.VariableDeclarator, ): void { - if (!node.id) { - return; - } reportInferrableType(node, node.id.typeAnnotation, node.init); } @@ -247,7 +244,7 @@ export default createRule({ | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression, ): void { - if (ignoreParameters || !node.params) { + if (ignoreParameters) { return; } @@ -256,11 +253,7 @@ export default createRule({ param = param.parameter; } - if ( - param.type === AST_NODE_TYPES.AssignmentPattern && - param.left && - param.right - ) { + if (param.type === AST_NODE_TYPES.AssignmentPattern) { reportInferrableType(param, param.left.typeAnnotation, param.right); } }); diff --git a/packages/eslint-plugin/src/rules/no-invalid-void-type.ts b/packages/eslint-plugin/src/rules/no-invalid-void-type.ts index fa849d8ac915..73cb181dd126 100644 --- a/packages/eslint-plugin/src/rules/no-invalid-void-type.ts +++ b/packages/eslint-plugin/src/rules/no-invalid-void-type.ts @@ -93,8 +93,8 @@ export default createRule<[Options], MessageIds>({ // extra check for precaution /* istanbul ignore next */ if ( - node.parent?.type !== AST_NODE_TYPES.TSTypeParameterInstantiation || - node.parent.parent?.type !== AST_NODE_TYPES.TSTypeReference + node.parent.type !== AST_NODE_TYPES.TSTypeParameterInstantiation || + node.parent.parent.type !== AST_NODE_TYPES.TSTypeReference ) { return; } @@ -158,7 +158,7 @@ export default createRule<[Options], MessageIds>({ (member.type === AST_NODE_TYPES.TSTypeReference && member.typeArguments?.type === AST_NODE_TYPES.TSTypeParameterInstantiation && - member.typeArguments?.params + member.typeArguments.params .map(param => param.type) .includes(AST_NODE_TYPES.TSVoidKeyword)), ); diff --git a/packages/eslint-plugin/src/rules/no-loop-func.ts b/packages/eslint-plugin/src/rules/no-loop-func.ts index 03f7662f9e33..5851ea3a8f93 100644 --- a/packages/eslint-plugin/src/rules/no-loop-func.ts +++ b/packages/eslint-plugin/src/rules/no-loop-func.ts @@ -211,7 +211,7 @@ function isSafe( return ( !upperRef.isWrite() || - (variable?.scope?.variableScope === upperRef.from.variableScope && + (variable?.scope.variableScope === upperRef.from.variableScope && id.range[0] < border) ); } diff --git a/packages/eslint-plugin/src/rules/no-magic-numbers.ts b/packages/eslint-plugin/src/rules/no-magic-numbers.ts index 54e559d3365c..bc738eb614b7 100644 --- a/packages/eslint-plugin/src/rules/no-magic-numbers.ts +++ b/packages/eslint-plugin/src/rules/no-magic-numbers.ts @@ -104,7 +104,7 @@ export default createRule({ let raw = node.raw; if ( - node.parent?.type === AST_NODE_TYPES.UnaryExpression && + node.parent.type === AST_NODE_TYPES.UnaryExpression && // the base rule only shows the operator for negative numbers // https://github.com/eslint/eslint/blob/9dfc8501fb1956c90dc11e6377b4cb38a6bea65d/lib/rules/no-magic-numbers.js#L126 node.parent.operator === '-' @@ -134,7 +134,7 @@ export default createRule({ */ function getLiteralParent(node: TSESTree.Literal): TSESTree.Node | undefined { if ( - node.parent?.type === AST_NODE_TYPES.UnaryExpression && + node.parent.type === AST_NODE_TYPES.UnaryExpression && ['-', '+'].includes(node.parent.operator) ) { return node.parent.parent; diff --git a/packages/eslint-plugin/src/rules/no-misused-promises.ts b/packages/eslint-plugin/src/rules/no-misused-promises.ts index 7fd6fb9ca71c..fa5f9ae5796b 100644 --- a/packages/eslint-plugin/src/rules/no-misused-promises.ts +++ b/packages/eslint-plugin/src/rules/no-misused-promises.ts @@ -3,7 +3,7 @@ import { AST_NODE_TYPES } from '@typescript-eslint/utils'; import * as tsutils from 'ts-api-utils'; import * as ts from 'typescript'; -import { createRule, getParserServices, getTypeArguments } from '../util'; +import { createRule, getParserServices } from '../util'; type Options = [ { @@ -556,7 +556,7 @@ function voidFunctionArguments( // Unwrap 'Array' to 'MaybeVoidFunction', // so that we'll handle it in the same way as a non-rest // 'param: MaybeVoidFunction' - type = getTypeArguments(type, checker)[0]; + type = checker.getTypeArguments(type)[0]; for (let i = index; i < node.arguments.length; i++) { checkThenableOrVoidArgument( checker, @@ -570,7 +570,7 @@ function voidFunctionArguments( } else if (checker.isTupleType(type)) { // Check each type in the tuple - for example, [boolean, () => void] would // add the index of the second tuple parameter to 'voidReturnIndices' - const typeArgs = getTypeArguments(type, checker); + const typeArgs = checker.getTypeArguments(type); for ( let i = index; i < node.arguments.length && i - index < typeArgs.length; diff --git a/packages/eslint-plugin/src/rules/no-mixed-enums.ts b/packages/eslint-plugin/src/rules/no-mixed-enums.ts index 71344fa5a689..65d9064eae0b 100644 --- a/packages/eslint-plugin/src/rules/no-mixed-enums.ts +++ b/packages/eslint-plugin/src/rules/no-mixed-enums.ts @@ -59,7 +59,7 @@ export default createRule({ } while (scope) { - scope.set.get(name)?.defs?.forEach(definition => { + scope.set.get(name)?.defs.forEach(definition => { if (definition.type === DefinitionType.ImportBinding) { found.imports.push(definition.node); } @@ -207,10 +207,7 @@ export default createRule({ desiredType ??= currentType; } - if ( - currentType !== desiredType && - (currentType !== undefined || desiredType === AllowedType.String) - ) { + if (currentType !== desiredType) { context.report({ messageId: 'mixed', node: member.initializer ?? member, diff --git a/packages/eslint-plugin/src/rules/no-non-null-assertion.ts b/packages/eslint-plugin/src/rules/no-non-null-assertion.ts index 6883b908bb54..40a0181191f9 100644 --- a/packages/eslint-plugin/src/rules/no-non-null-assertion.ts +++ b/packages/eslint-plugin/src/rules/no-non-null-assertion.ts @@ -58,7 +58,7 @@ export default createRule<[], MessageIds>({ } if ( - node.parent?.type === AST_NODE_TYPES.MemberExpression && + node.parent.type === AST_NODE_TYPES.MemberExpression && node.parent.object === node ) { if (!node.parent.optional) { @@ -91,7 +91,7 @@ export default createRule<[], MessageIds>({ } } } else if ( - node.parent?.type === AST_NODE_TYPES.CallExpression && + node.parent.type === AST_NODE_TYPES.CallExpression && node.parent.callee === node ) { if (!node.parent.optional) { diff --git a/packages/eslint-plugin/src/rules/no-redeclare.ts b/packages/eslint-plugin/src/rules/no-redeclare.ts index 9b404e6d8424..fefd8e10b3e8 100644 --- a/packages/eslint-plugin/src/rules/no-redeclare.ts +++ b/packages/eslint-plugin/src/rules/no-redeclare.ts @@ -74,7 +74,7 @@ export default createRule({ void > { if ( - options?.builtinGlobals && + options.builtinGlobals && 'eslintImplicitGlobalSetting' in variable && (variable.eslintImplicitGlobalSetting === 'readonly' || variable.eslintImplicitGlobalSetting === 'writable') diff --git a/packages/eslint-plugin/src/rules/no-redundant-type-constituents.ts b/packages/eslint-plugin/src/rules/no-redundant-type-constituents.ts index f38d6c6ad6f1..a9b22e71de11 100644 --- a/packages/eslint-plugin/src/rules/no-redundant-type-constituents.ts +++ b/packages/eslint-plugin/src/rules/no-redundant-type-constituents.ts @@ -170,7 +170,7 @@ function describeLiteralTypeNode(typeNode: TSESTree.TypeNode): string { function isNodeInsideReturnType(node: TSESTree.TSUnionType): boolean { return !!( - node.parent?.type === AST_NODE_TYPES.TSTypeAnnotation && + node.parent.type === AST_NODE_TYPES.TSTypeAnnotation && (isFunctionType(node.parent.parent) || isFunction(node.parent.parent)) ); } diff --git a/packages/eslint-plugin/src/rules/no-shadow.ts b/packages/eslint-plugin/src/rules/no-shadow.ts index 9e2359e8b9f1..3f6e70018484 100644 --- a/packages/eslint-plugin/src/rules/no-shadow.ts +++ b/packages/eslint-plugin/src/rules/no-shadow.ts @@ -126,7 +126,7 @@ export default createRule({ return false; } - const [firstDefinition] = shadowed.defs; + const firstDefinition = shadowed.defs.at(0); const isShadowedValue = !('isValueVariable' in shadowed) || !firstDefinition || @@ -175,25 +175,24 @@ export default createRule({ } const typeParameter = variable.identifiers[0].parent; - if (typeParameter?.type !== AST_NODE_TYPES.TSTypeParameter) { + if (typeParameter.type !== AST_NODE_TYPES.TSTypeParameter) { return false; } const typeParameterDecl = typeParameter.parent; if ( - typeParameterDecl?.type !== AST_NODE_TYPES.TSTypeParameterDeclaration + typeParameterDecl.type !== AST_NODE_TYPES.TSTypeParameterDeclaration ) { return false; } const functionExpr = typeParameterDecl.parent; if ( - !functionExpr || - (functionExpr.type !== AST_NODE_TYPES.FunctionExpression && - functionExpr.type !== AST_NODE_TYPES.TSEmptyBodyFunctionExpression) + functionExpr.type !== AST_NODE_TYPES.FunctionExpression && + functionExpr.type !== AST_NODE_TYPES.TSEmptyBodyFunctionExpression ) { return false; } const methodDefinition = functionExpr.parent; - if (methodDefinition?.type !== AST_NODE_TYPES.MethodDefinition) { + if (methodDefinition.type !== AST_NODE_TYPES.MethodDefinition) { return false; } return methodDefinition.static; @@ -214,19 +213,19 @@ export default createRule({ } const typeParameter = variable.identifiers[0].parent; - if (typeParameter?.type !== AST_NODE_TYPES.TSTypeParameter) { + if (typeParameter.type !== AST_NODE_TYPES.TSTypeParameter) { return false; } const typeParameterDecl = typeParameter.parent; if ( - typeParameterDecl?.type !== AST_NODE_TYPES.TSTypeParameterDeclaration + typeParameterDecl.type !== AST_NODE_TYPES.TSTypeParameterDeclaration ) { return false; } const classDecl = typeParameterDecl.parent; return ( - classDecl?.type === AST_NODE_TYPES.ClassDeclaration || - classDecl?.type === AST_NODE_TYPES.ClassExpression + classDecl.type === AST_NODE_TYPES.ClassDeclaration || + classDecl.type === AST_NODE_TYPES.ClassExpression ); } @@ -251,7 +250,6 @@ export default createRule({ ): boolean { return ( scope.type === ScopeType.tsModule && - scope.block.type === AST_NODE_TYPES.TSModuleDeclaration && scope.block.id.type === AST_NODE_TYPES.Literal && scope.block.id.value === name ); @@ -273,7 +271,7 @@ export default createRule({ firstDefinition.parent.source.value, ) && secondDefinition.node.type === AST_NODE_TYPES.TSInterfaceDeclaration && - secondDefinition.node.parent?.type === + secondDefinition.node.parent.type === AST_NODE_TYPES.ExportNamedDeclaration ); } @@ -382,7 +380,7 @@ export default createRule({ variable: TSESLint.Scope.Variable, shadowedVariable: TSESLint.Scope.Variable, ): boolean { - const outerDef = shadowedVariable.defs[0]; + const outerDef = shadowedVariable.defs.at(0); if (!outerDef) { return false; @@ -416,14 +414,15 @@ export default createRule({ let node: TSESTree.Node | undefined = outerDef.name; const location = callExpression.range[1]; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (node) { if (node.type === AST_NODE_TYPES.VariableDeclarator) { if (isInRange(node.init, location)) { return true; } if ( - (node.parent?.parent?.type === AST_NODE_TYPES.ForInStatement || - node.parent?.parent?.type === AST_NODE_TYPES.ForOfStatement) && + (node.parent.parent?.type === AST_NODE_TYPES.ForInStatement || + node.parent.parent?.type === AST_NODE_TYPES.ForOfStatement) && isInRange(node.parent.parent.right, location) ) { return true; @@ -468,10 +467,10 @@ export default createRule({ scopeVar: TSESLint.Scope.Variable, ): boolean { const outerScope = scopeVar.scope; - const outerDef = scopeVar.defs[0]; + const outerDef = scopeVar.defs.at(0); const outer = outerDef?.parent?.range; const innerScope = variable.scope; - const innerDef = variable.defs[0]; + const innerDef = variable.defs.at(0); const inner = innerDef?.name.range; return !!( @@ -494,7 +493,7 @@ export default createRule({ function getNameRange( variable: TSESLint.Scope.Variable, ): TSESTree.Range | undefined { - const def = variable.defs[0]; + const def = variable.defs.at(0); return def?.name.range; } @@ -508,7 +507,7 @@ export default createRule({ variable: TSESLint.Scope.Variable, scopeVar: TSESLint.Scope.Variable, ): boolean { - const outerDef = scopeVar.defs[0]; + const outerDef = scopeVar.defs.at(0); const inner = getNameRange(variable); const outer = getNameRange(scopeVar); @@ -531,7 +530,7 @@ export default createRule({ function getDeclaredLocation( variable: TSESLint.Scope.Variable, ): { global: false; line: number; column: number } | { global: true } { - const identifier = variable.identifiers[0]; + const identifier = variable.identifiers.at(0); if (identifier) { return { global: false, diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-boolean-literal-compare.ts b/packages/eslint-plugin/src/rules/no-unnecessary-boolean-literal-compare.ts index 9a25eeb5f415..254788abcab2 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-boolean-literal-compare.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-boolean-literal-compare.ts @@ -222,8 +222,7 @@ export default createRule({ // 2. literalBooleanInComparison - is compared to literal boolean // 3. negated - is expression negated - const isUnaryNegation = - node.parent != null && nodeIsUnaryNegation(node.parent); + const isUnaryNegation = nodeIsUnaryNegation(node.parent); const shouldNegate = comparison.negated !== comparison.literalBooleanInComparison; diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts index c5de895264ed..4da9a8bc9fe0 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts @@ -438,9 +438,8 @@ export default createRule({ const callback = node.arguments[0]!; // Inline defined functions if ( - (callback.type === AST_NODE_TYPES.ArrowFunctionExpression || - callback.type === AST_NODE_TYPES.FunctionExpression) && - callback.body + callback.type === AST_NODE_TYPES.ArrowFunctionExpression || + callback.type === AST_NODE_TYPES.FunctionExpression ) { // Two special cases, where we can directly check the node that's returned: // () => something diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts b/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts index d766257d6c6c..e10ee7b1b39b 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-type-arguments.ts @@ -6,7 +6,6 @@ import { createRule, findFirstResult, getParserServices, - getTypeArguments, isTypeReferenceType, } from '../util'; @@ -51,7 +50,7 @@ export default createRule<[], MessageIds>({ if (isTypeReferenceType(type)) { return { type: type.target, - typeArguments: getTypeArguments(type, checker), + typeArguments: checker.getTypeArguments(type), }; } return { @@ -67,7 +66,7 @@ export default createRule<[], MessageIds>({ // Just check the last one. Must specify previous type parameters if the last one is specified. const i = esParameters.params.length - 1; const arg = esParameters.params[i]; - const param = typeParameters[i]; + const param = typeParameters.at(i); if (!param?.default) { return; } diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts index 6029cf192da3..e108c7acb300 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts @@ -141,7 +141,7 @@ export default createRule({ return { TSNonNullExpression(node): void { if ( - node.parent?.type === AST_NODE_TYPES.AssignmentExpression && + node.parent.type === AST_NODE_TYPES.AssignmentExpression && node.parent.operator === '=' ) { if (node.parent.left === node) { diff --git a/packages/eslint-plugin/src/rules/no-unsafe-argument.ts b/packages/eslint-plugin/src/rules/no-unsafe-argument.ts index fe74d1360969..a04440f383c3 100644 --- a/packages/eslint-plugin/src/rules/no-unsafe-argument.ts +++ b/packages/eslint-plugin/src/rules/no-unsafe-argument.ts @@ -5,7 +5,6 @@ import * as ts from 'typescript'; import { createRule, getParserServices, - getTypeArguments, isTypeAnyArrayType, isTypeAnyType, isUnsafeAssignment, @@ -64,13 +63,13 @@ class FunctionSignature { // is a rest param if (checker.isArrayType(type)) { restType = { - type: getTypeArguments(type, checker)[0], + type: checker.getTypeArguments(type)[0], kind: RestTypeKind.Array, index: i, }; } else if (checker.isTupleType(type)) { restType = { - typeArguments: getTypeArguments(type, checker), + typeArguments: checker.getTypeArguments(type), kind: RestTypeKind.Tuple, index: i, }; @@ -205,10 +204,8 @@ export default createRule<[], MessageIds>({ }); } else if (checker.isTupleType(spreadArgType)) { // foo(...[tuple1, tuple2]) - const spreadTypeArguments = getTypeArguments( - spreadArgType, - checker, - ); + const spreadTypeArguments = + checker.getTypeArguments(spreadArgType); for (const tupleType of spreadTypeArguments) { const parameterType = signature.getNextParameterType(); if (parameterType == null) { diff --git a/packages/eslint-plugin/src/rules/no-unsafe-assignment.ts b/packages/eslint-plugin/src/rules/no-unsafe-assignment.ts index c16a4904756b..4ce2f6db99a3 100644 --- a/packages/eslint-plugin/src/rules/no-unsafe-assignment.ts +++ b/packages/eslint-plugin/src/rules/no-unsafe-assignment.ts @@ -9,7 +9,6 @@ import { getContextualType, getParserServices, getThisExpression, - getTypeArguments, isTypeAnyArrayType, isTypeAnyType, isTypeUnknownType, @@ -97,7 +96,7 @@ export default createRule({ return true; } - const tupleElements = getTypeArguments(senderType, checker); + const tupleElements = checker.getTypeArguments(senderType); // tuple with any // const [x] = [1 as any]; diff --git a/packages/eslint-plugin/src/rules/no-unused-vars.ts b/packages/eslint-plugin/src/rules/no-unused-vars.ts index eec4e9d6ef4f..bb00cb3c67df 100644 --- a/packages/eslint-plugin/src/rules/no-unused-vars.ts +++ b/packages/eslint-plugin/src/rules/no-unused-vars.ts @@ -109,46 +109,44 @@ export default createRule({ caughtErrors: 'none', }; - if (firstOption) { - if (typeof firstOption === 'string') { - options.vars = firstOption; - } else { - options.vars = firstOption.vars ?? options.vars; - options.args = firstOption.args ?? options.args; - options.ignoreRestSiblings = - firstOption.ignoreRestSiblings ?? options.ignoreRestSiblings; - options.caughtErrors = - firstOption.caughtErrors ?? options.caughtErrors; - - if (firstOption.varsIgnorePattern) { - options.varsIgnorePattern = new RegExp( - firstOption.varsIgnorePattern, - 'u', - ); - } + if (typeof firstOption === 'string') { + options.vars = firstOption; + } else { + options.vars = firstOption.vars ?? options.vars; + options.args = firstOption.args ?? options.args; + options.ignoreRestSiblings = + firstOption.ignoreRestSiblings ?? options.ignoreRestSiblings; + options.caughtErrors = firstOption.caughtErrors ?? options.caughtErrors; + + if (firstOption.varsIgnorePattern) { + options.varsIgnorePattern = new RegExp( + firstOption.varsIgnorePattern, + 'u', + ); + } - if (firstOption.argsIgnorePattern) { - options.argsIgnorePattern = new RegExp( - firstOption.argsIgnorePattern, - 'u', - ); - } + if (firstOption.argsIgnorePattern) { + options.argsIgnorePattern = new RegExp( + firstOption.argsIgnorePattern, + 'u', + ); + } - if (firstOption.caughtErrorsIgnorePattern) { - options.caughtErrorsIgnorePattern = new RegExp( - firstOption.caughtErrorsIgnorePattern, - 'u', - ); - } + if (firstOption.caughtErrorsIgnorePattern) { + options.caughtErrorsIgnorePattern = new RegExp( + firstOption.caughtErrorsIgnorePattern, + 'u', + ); + } - if (firstOption.destructuredArrayIgnorePattern) { - options.destructuredArrayIgnorePattern = new RegExp( - firstOption.destructuredArrayIgnorePattern, - 'u', - ); - } + if (firstOption.destructuredArrayIgnorePattern) { + options.destructuredArrayIgnorePattern = new RegExp( + firstOption.destructuredArrayIgnorePattern, + 'u', + ); } } + return options; })(); @@ -161,7 +159,7 @@ export default createRule({ function hasRestSibling(node: TSESTree.Node): boolean { return ( node.type === AST_NODE_TYPES.Property && - node.parent?.type === AST_NODE_TYPES.ObjectPattern && + node.parent.type === AST_NODE_TYPES.ObjectPattern && node.parent.properties[node.parent.properties.length - 1].type === AST_NODE_TYPES.RestElement ); @@ -224,12 +222,12 @@ export default createRule({ } const refUsedInArrayPatterns = variable.references.some( - ref => ref.identifier.parent?.type === AST_NODE_TYPES.ArrayPattern, + ref => ref.identifier.parent.type === AST_NODE_TYPES.ArrayPattern, ); // skip elements of array destructuring patterns if ( - (def.name.parent?.type === AST_NODE_TYPES.ArrayPattern || + (def.name.parent.type === AST_NODE_TYPES.ArrayPattern || refUsedInArrayPatterns) && 'name' in def.name && options.destructuredArrayIgnorePattern?.test(def.name.name) @@ -339,7 +337,7 @@ export default createRule({ false, )](node: DeclarationSelectorNode): void { const moduleDecl = nullThrows( - node.parent?.parent, + node.parent.parent, NullThrowsReasons.MissingParent, ) as TSESTree.TSModuleDeclaration; @@ -366,7 +364,7 @@ export default createRule({ function getDefinedMessageData( unusedVar: TSESLint.Scope.Variable, ): Record { - const defType = unusedVar?.defs[0]?.type; + const defType = unusedVar.defs[0]?.type; let type; let pattern; @@ -410,12 +408,12 @@ export default createRule({ function getAssignedMessageData( unusedVar: TSESLint.Scope.Variable, ): Record { - const def = unusedVar.defs[0]; + const def = unusedVar.defs.at(0); let additional = ''; if ( options.destructuredArrayIgnorePattern && - def?.name.parent?.type === AST_NODE_TYPES.ArrayPattern + def?.name.parent.type === AST_NODE_TYPES.ArrayPattern ) { additional = `. Allowed unused elements of array destructuring patterns must match ${options.destructuredArrayIgnorePattern.toString()}`; } else if (options.varsIgnorePattern) { @@ -480,7 +478,7 @@ export default createRule({ return cached; } - if (node.body && node.body.type === AST_NODE_TYPES.TSModuleBlock) { + if (node.body) { for (const statement of node.body.body) { if (statement.type === AST_NODE_TYPES.TSExportAssignment) { MODULE_DECL_CACHE.set(node, true); diff --git a/packages/eslint-plugin/src/rules/no-use-before-define.ts b/packages/eslint-plugin/src/rules/no-use-before-define.ts index 67f6ee524b86..de0351b8209f 100644 --- a/packages/eslint-plugin/src/rules/no-use-before-define.ts +++ b/packages/eslint-plugin/src/rules/no-use-before-define.ts @@ -101,7 +101,7 @@ function isOuterVariable( function isNamedExports(reference: TSESLint.Scope.Reference): boolean { const { identifier } = reference; return ( - identifier.parent?.type === AST_NODE_TYPES.ExportSpecifier && + identifier.parent.type === AST_NODE_TYPES.ExportSpecifier && identifier.parent.local === identifier ); } @@ -152,12 +152,8 @@ function isClassRefInClassDecorator( variable: TSESLint.Scope.Variable, reference: TSESLint.Scope.Reference, ): boolean { - if (variable.defs[0].type !== DefinitionType.ClassName) { - return false; - } - if ( - !variable.defs[0].node.decorators || + variable.defs[0].type !== DefinitionType.ClassName || variable.defs[0].node.decorators.length === 0 ) { return false; @@ -202,9 +198,8 @@ function isInInitializer( return true; } if ( - node.parent?.parent && - (node.parent.parent.type === AST_NODE_TYPES.ForInStatement || - node.parent.parent.type === AST_NODE_TYPES.ForOfStatement) && + (node.parent.parent?.type === AST_NODE_TYPES.ForInStatement || + node.parent.parent?.type === AST_NODE_TYPES.ForOfStatement) && isInRange(node.parent.parent.right, location) ) { return true; diff --git a/packages/eslint-plugin/src/rules/no-useless-constructor.ts b/packages/eslint-plugin/src/rules/no-useless-constructor.ts index 8066674e5408..f7d4970a381d 100644 --- a/packages/eslint-plugin/src/rules/no-useless-constructor.ts +++ b/packages/eslint-plugin/src/rules/no-useless-constructor.ts @@ -64,8 +64,7 @@ export default createRule({ return { MethodDefinition(node): void { if ( - node.value?.type === AST_NODE_TYPES.FunctionExpression && - node.value.body && + node.value.type === AST_NODE_TYPES.FunctionExpression && checkAccessibility(node) && checkParams(node) ) { diff --git a/packages/eslint-plugin/src/rules/no-var-requires.ts b/packages/eslint-plugin/src/rules/no-var-requires.ts index 61a300678215..607ec34d7528 100644 --- a/packages/eslint-plugin/src/rules/no-var-requires.ts +++ b/packages/eslint-plugin/src/rules/no-var-requires.ts @@ -26,12 +26,11 @@ export default createRule({ node: TSESTree.CallExpression, ): void { const parent = - node.parent?.type === AST_NODE_TYPES.ChainExpression + node.parent.type === AST_NODE_TYPES.ChainExpression ? node.parent.parent : node.parent; if ( - parent && [ AST_NODE_TYPES.CallExpression, AST_NODE_TYPES.MemberExpression, diff --git a/packages/eslint-plugin/src/rules/padding-line-between-statements.ts b/packages/eslint-plugin/src/rules/padding-line-between-statements.ts index 255ceb0c712a..466a0e9872cc 100644 --- a/packages/eslint-plugin/src/rules/padding-line-between-statements.ts +++ b/packages/eslint-plugin/src/rules/padding-line-between-statements.ts @@ -127,9 +127,7 @@ function newNodeTypeTester(type: AST_NODE_TYPES): NodeTestObject { * @private */ function skipChainExpression(node: TSESTree.Node): TSESTree.Node { - return node && node.type === AST_NODE_TYPES.ChainExpression - ? node.expression - : node; + return node.type === AST_NODE_TYPES.ChainExpression ? node.expression : node; } /** @@ -163,9 +161,9 @@ function isIIFEStatement(node: TSESTree.Node): boolean { */ function isCJSRequire(node: TSESTree.Node): boolean { if (node.type === AST_NODE_TYPES.VariableDeclaration) { - const declaration = node.declarations[0]; + const declaration = node.declarations.at(0); if (declaration?.init) { - let call = declaration?.init; + let call = declaration.init; while (call.type === AST_NODE_TYPES.MemberExpression) { call = call.object; } @@ -234,8 +232,8 @@ function isDirective( ): boolean { return ( node.type === AST_NODE_TYPES.ExpressionStatement && - (node.parent?.type === AST_NODE_TYPES.Program || - (node.parent?.type === AST_NODE_TYPES.BlockStatement && + (node.parent.type === AST_NODE_TYPES.Program || + (node.parent.type === AST_NODE_TYPES.BlockStatement && isFunction(node.parent.parent))) && node.expression.type === AST_NODE_TYPES.Literal && typeof node.expression.value === 'string' && @@ -478,7 +476,7 @@ function verifyForAlways( } return true; }, - })! || nextNode; + }) || nextNode; const insertText = isTokenOnSameLine(prevToken, nextToken) ? '\n\n' : '\n'; @@ -647,7 +645,7 @@ export default createRule({ create(context) { const sourceCode = context.getSourceCode(); // eslint-disable-next-line no-restricted-syntax -- We need all raw options. - const configureList = context.options || []; + const configureList = context.options; type Scope = { upper: Scope; diff --git a/packages/eslint-plugin/src/rules/prefer-for-of.ts b/packages/eslint-plugin/src/rules/prefer-for-of.ts index a7ee36868bd9..dc45e41e420f 100644 --- a/packages/eslint-plugin/src/rules/prefer-for-of.ts +++ b/packages/eslint-plugin/src/rules/prefer-for-of.ts @@ -147,7 +147,7 @@ export default createRule({ if ( parent.type === AST_NODE_TYPES.Property && parent.value === node && - parent.parent?.type === AST_NODE_TYPES.ObjectExpression && + parent.parent.type === AST_NODE_TYPES.ObjectExpression && isAssignee(parent.parent) ) { return true; @@ -168,8 +168,7 @@ export default createRule({ const node = id.parent; return ( !contains(body, id) || - (node !== undefined && - node.type === AST_NODE_TYPES.MemberExpression && + (node.type === AST_NODE_TYPES.MemberExpression && node.object.type !== AST_NODE_TYPES.ThisExpression && node.property === id && sourceCode.getText(node.object) === arrayText && diff --git a/packages/eslint-plugin/src/rules/prefer-function-type.ts b/packages/eslint-plugin/src/rules/prefer-function-type.ts index 9655093236eb..b4f00dec0cb4 100644 --- a/packages/eslint-plugin/src/rules/prefer-function-type.ts +++ b/packages/eslint-plugin/src/rules/prefer-function-type.ts @@ -35,7 +35,7 @@ export default createRule({ * @param node The node being checked */ function hasOneSupertype(node: TSESTree.TSInterfaceDeclaration): boolean { - if (!node.extends || node.extends.length === 0) { + if (node.extends.length === 0) { return false; } if (node.extends.length !== 1) { diff --git a/packages/eslint-plugin/src/rules/prefer-includes.ts b/packages/eslint-plugin/src/rules/prefer-includes.ts index 65f717c4126a..ef7ed54ee59d 100644 --- a/packages/eslint-plugin/src/rules/prefer-includes.ts +++ b/packages/eslint-plugin/src/rules/prefer-includes.ts @@ -152,7 +152,7 @@ export default createRule({ // Check if the comparison is equivalent to `includes()`. const callNode = node.parent as TSESTree.CallExpression; const compareNode = ( - callNode.parent?.type === AST_NODE_TYPES.ChainExpression + callNode.parent.type === AST_NODE_TYPES.ChainExpression ? callNode.parent.parent : callNode.parent ) as TSESTree.BinaryExpression; diff --git a/packages/eslint-plugin/src/rules/prefer-namespace-keyword.ts b/packages/eslint-plugin/src/rules/prefer-namespace-keyword.ts index 0c945a6b29d5..8eb1422a0710 100644 --- a/packages/eslint-plugin/src/rules/prefer-namespace-keyword.ts +++ b/packages/eslint-plugin/src/rules/prefer-namespace-keyword.ts @@ -25,7 +25,7 @@ export default createRule({ return { TSModuleDeclaration(node): void { // Do nothing if the name is a string. - if (!node.id || node.id.type === AST_NODE_TYPES.Literal) { + if (node.id.type === AST_NODE_TYPES.Literal) { return; } // Get tokens of the declaration header. diff --git a/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts b/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts index e9e340f93240..f90c1ac23968 100644 --- a/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts +++ b/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts @@ -357,7 +357,7 @@ export default createRule({ function* fix( fixer: TSESLint.RuleFixer, ): IterableIterator { - if (node.parent && isLogicalOrOperator(node.parent)) { + if (isLogicalOrOperator(node.parent)) { // '&&' and '??' operations cannot be mixed without parentheses (e.g. a && b ?? c) if ( node.left.type === AST_NODE_TYPES.LogicalExpression && @@ -433,7 +433,7 @@ function isMixedLogicalExpression(node: TSESTree.LogicalExpression): boolean { } seen.add(current); - if (current && current.type === AST_NODE_TYPES.LogicalExpression) { + if (current.type === AST_NODE_TYPES.LogicalExpression) { if (current.operator === '&&') { return true; } else if (current.operator === '||') { diff --git a/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/analyzeChain.ts b/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/analyzeChain.ts index dea7b6f490b7..cc5d3e91f53e 100644 --- a/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/analyzeChain.ts +++ b/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/analyzeChain.ts @@ -553,7 +553,7 @@ export function analyzeChain( subChain.push(currentOperand); } else if (comparisonResult === NodeComparisonResult.Invalid) { maybeReportThenReset(validatedOperands); - } else if (comparisonResult === NodeComparisonResult.Equal) { + } else { // purposely don't push this case because the node is a no-op and if // we consider it then we might report on things like // foo && foo diff --git a/packages/eslint-plugin/src/rules/prefer-optional-chain.ts b/packages/eslint-plugin/src/rules/prefer-optional-chain.ts index a1e9bb95f22d..3094da283846 100644 --- a/packages/eslint-plugin/src/rules/prefer-optional-chain.ts +++ b/packages/eslint-plugin/src/rules/prefer-optional-chain.ts @@ -120,7 +120,6 @@ export default createRule< rightNode.properties.length === 0; if ( !isRightNodeAnEmptyObjectLiteral || - !parentNode || parentNode.type !== AST_NODE_TYPES.MemberExpression || parentNode.optional ) { diff --git a/packages/eslint-plugin/src/rules/prefer-readonly.ts b/packages/eslint-plugin/src/rules/prefer-readonly.ts index b9980536fb23..7d5591b11680 100644 --- a/packages/eslint-plugin/src/rules/prefer-readonly.ts +++ b/packages/eslint-plugin/src/rules/prefer-readonly.ts @@ -106,6 +106,7 @@ export default createRule({ ): boolean { let current: ts.Node = node.parent; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (current) { const parent = current.parent; diff --git a/packages/eslint-plugin/src/rules/prefer-regexp-exec.ts b/packages/eslint-plugin/src/rules/prefer-regexp-exec.ts index 7bbf5feba250..b3c7aa7ba314 100644 --- a/packages/eslint-plugin/src/rules/prefer-regexp-exec.ts +++ b/packages/eslint-plugin/src/rules/prefer-regexp-exec.ts @@ -80,10 +80,9 @@ export default createRule({ node.type === AST_NODE_TYPES.CallExpression || node.type === AST_NODE_TYPES.NewExpression ) { - const [, flags] = node.arguments; - return ( - flags && - flags.type === AST_NODE_TYPES.Literal && + const flags = node.arguments.at(1); + return !!( + flags?.type === AST_NODE_TYPES.Literal && typeof flags.value === 'string' && flags.value.includes('g') ); diff --git a/packages/eslint-plugin/src/rules/prefer-return-this-type.ts b/packages/eslint-plugin/src/rules/prefer-return-this-type.ts index bc8375d7a7dc..80e55427078d 100644 --- a/packages/eslint-plugin/src/rules/prefer-return-this-type.ts +++ b/packages/eslint-plugin/src/rules/prefer-return-this-type.ts @@ -60,11 +60,9 @@ export default createRule({ } function isThisSpecifiedInParameters(originalFunc: FunctionLike): boolean { - const firstArg = originalFunc.params[0]; - return ( - firstArg && - firstArg.type === AST_NODE_TYPES.Identifier && - firstArg.name === 'this' + const firstArg = originalFunc.params.at(0); + return !!( + firstArg?.type === AST_NODE_TYPES.Identifier && firstArg.name === 'this' ); } @@ -92,7 +90,7 @@ export default createRule({ } let hasReturnThis = false; - let hasReturnClassType = false; + let hasReturnClassType = false as boolean; forEachReturnStatement(func.body as ts.Block, stmt => { const expr = stmt.expression; diff --git a/packages/eslint-plugin/src/rules/prefer-string-starts-ends-with.ts b/packages/eslint-plugin/src/rules/prefer-string-starts-ends-with.ts index 82451e181320..47995fb4befc 100644 --- a/packages/eslint-plugin/src/rules/prefer-string-starts-ends-with.ts +++ b/packages/eslint-plugin/src/rules/prefer-string-starts-ends-with.ts @@ -384,7 +384,7 @@ export default createRule({ let parentNode = getParent(node); let indexNode: TSESTree.Node | null = null; - if (parentNode?.type === AST_NODE_TYPES.CallExpression) { + if (parentNode.type === AST_NODE_TYPES.CallExpression) { if (parentNode.arguments.length === 1) { indexNode = parentNode.arguments[0]; } diff --git a/packages/eslint-plugin/src/rules/quotes.ts b/packages/eslint-plugin/src/rules/quotes.ts index 74c41d6130d0..89100ef01ac7 100644 --- a/packages/eslint-plugin/src/rules/quotes.ts +++ b/packages/eslint-plugin/src/rules/quotes.ts @@ -40,7 +40,7 @@ export default createRule({ function isAllowedAsNonBacktick(node: TSESTree.Literal): boolean { const parent = node.parent; - switch (parent?.type) { + switch (parent.type) { case AST_NODE_TYPES.TSAbstractMethodDefinition: case AST_NODE_TYPES.TSMethodSignature: case AST_NODE_TYPES.TSPropertySignature: diff --git a/packages/eslint-plugin/src/rules/require-array-sort-compare.ts b/packages/eslint-plugin/src/rules/require-array-sort-compare.ts index 4097362bb247..1b2916ea0b48 100644 --- a/packages/eslint-plugin/src/rules/require-array-sort-compare.ts +++ b/packages/eslint-plugin/src/rules/require-array-sort-compare.ts @@ -4,7 +4,6 @@ import { createRule, getConstrainedTypeAtLocation, getParserServices, - getTypeArguments, getTypeName, isTypeArrayTypeOrUnionOfArrayTypes, } from '../util'; @@ -61,7 +60,7 @@ export default createRule({ const type = services.getTypeAtLocation(node); if (checker.isArrayType(type) || checker.isTupleType(type)) { - const typeArgs = getTypeArguments(type, checker); + const typeArgs = checker.getTypeArguments(type); return typeArgs.every(arg => getTypeName(checker, arg) === 'string'); } return false; diff --git a/packages/eslint-plugin/src/rules/require-await.ts b/packages/eslint-plugin/src/rules/require-await.ts index 86049b04e587..61d5644a2d11 100644 --- a/packages/eslint-plugin/src/rules/require-await.ts +++ b/packages/eslint-plugin/src/rules/require-await.ts @@ -161,7 +161,7 @@ export default createRule({ >, ): void { const expression = services.esTreeNodeToTSNodeMap.get(node); - if (expression && isThenableType(expression)) { + if (isThenableType(expression)) { markAsHasAwait(); } }, @@ -182,7 +182,7 @@ export default createRule({ function isEmptyFunction(node: FunctionNode): boolean { return ( - node.body?.type === AST_NODE_TYPES.BlockStatement && + node.body.type === AST_NODE_TYPES.BlockStatement && node.body.body.length === 0 ); } diff --git a/packages/eslint-plugin/src/rules/return-await.ts b/packages/eslint-plugin/src/rules/return-await.ts index df0810d41c05..ab8f09b417ab 100644 --- a/packages/eslint-plugin/src/rules/return-await.ts +++ b/packages/eslint-plugin/src/rules/return-await.ts @@ -72,6 +72,7 @@ export default createRule({ function inTry(node: ts.Node): boolean { let ancestor = node.parent; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if (ts.isTryStatement(ancestor)) { return true; @@ -86,6 +87,7 @@ export default createRule({ function inCatch(node: ts.Node): boolean { let ancestor = node.parent; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if (ts.isCatchClause(ancestor)) { return true; @@ -100,6 +102,7 @@ export default createRule({ function isReturnPromiseInFinally(node: ts.Node): boolean { let ancestor = node.parent; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if ( ts.isTryStatement(ancestor.parent) && @@ -117,6 +120,7 @@ export default createRule({ function hasFinallyBlock(node: ts.Node): boolean { let ancestor = node.parent; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if (ts.isTryStatement(ancestor)) { return !!ancestor.finallyBlock; @@ -310,7 +314,7 @@ export default createRule({ } }, ReturnStatement(node): void { - const scopeInfo = scopeInfoStack[scopeInfoStack.length - 1]; + const scopeInfo = scopeInfoStack.at(-1); if (!scopeInfo?.hasAsync || !node.argument) { return; } diff --git a/packages/eslint-plugin/src/rules/sort-type-constituents.ts b/packages/eslint-plugin/src/rules/sort-type-constituents.ts index 552599312e19..1491ebad4267 100644 --- a/packages/eslint-plugin/src/rules/sort-type-constituents.ts +++ b/packages/eslint-plugin/src/rules/sort-type-constituents.ts @@ -211,7 +211,7 @@ export default createRule({ ? 'Intersection' : 'Union', }; - if (node.parent?.type === AST_NODE_TYPES.TSTypeAliasDeclaration) { + if (node.parent.type === AST_NODE_TYPES.TSTypeAliasDeclaration) { messageId = 'notSortedNamed'; data.name = node.parent.id.name; } diff --git a/packages/eslint-plugin/src/rules/triple-slash-reference.ts b/packages/eslint-plugin/src/rules/triple-slash-reference.ts index 22f6b49da617..0eda64ce1b55 100644 --- a/packages/eslint-plugin/src/rules/triple-slash-reference.ts +++ b/packages/eslint-plugin/src/rules/triple-slash-reference.ts @@ -54,7 +54,7 @@ export default createRule({ }, ], create(context, [{ lib, path, types }]) { - let programNode: TSESTree.Node; + let programNode: TSESTree.Node | undefined; const sourceCode = context.getSourceCode(); const references: { comment: TSESTree.Comment; diff --git a/packages/eslint-plugin/src/rules/type-annotation-spacing.ts b/packages/eslint-plugin/src/rules/type-annotation-spacing.ts index f9ca288649e0..b5bcc59e7de4 100644 --- a/packages/eslint-plugin/src/rules/type-annotation-spacing.ts +++ b/packages/eslint-plugin/src/rules/type-annotation-spacing.ts @@ -48,21 +48,21 @@ function createRules(options?: Config): WhitespaceRules { const colon = { ...{ before: false, after: true }, ...globals, - ...override?.colon, + ...override.colon, }; const arrow = { ...{ before: true, after: true }, ...globals, - ...override?.arrow, + ...override.arrow, }; return { colon: colon, arrow: arrow, - variable: { ...colon, ...override?.variable }, - property: { ...colon, ...override?.property }, - parameter: { ...colon, ...override?.parameter }, - returnType: { ...colon, ...override?.returnType }, + variable: { ...colon, ...override.variable }, + property: { ...colon, ...override.property }, + parameter: { ...colon, ...override.parameter }, + returnType: { ...colon, ...override.returnType }, }; } @@ -84,7 +84,7 @@ function getRules( rules: WhitespaceRules, node: TSESTree.TypeNode, ): WhitespaceRule { - const scope = node?.parent?.parent; + const scope = node.parent.parent; if (isTSFunctionType(scope) || isTSConstructorType(scope)) { return rules.arrow; diff --git a/packages/eslint-plugin/src/rules/typedef.ts b/packages/eslint-plugin/src/rules/typedef.ts index e84aaef8cb3d..187f4d620365 100644 --- a/packages/eslint-plugin/src/rules/typedef.ts +++ b/packages/eslint-plugin/src/rules/typedef.ts @@ -124,10 +124,7 @@ export default createRule<[Options], MessageIds>({ annotationNode = param.parameter; // Check TS parameter property with default value like `constructor(private param: string = 'something') {}` - if ( - annotationNode && - annotationNode.type === AST_NODE_TYPES.AssignmentPattern - ) { + if (annotationNode.type === AST_NODE_TYPES.AssignmentPattern) { annotationNode = annotationNode.left; } @@ -137,7 +134,7 @@ export default createRule<[Options], MessageIds>({ break; } - if (annotationNode !== undefined && !annotationNode.typeAnnotation) { + if (!annotationNode.typeAnnotation) { report(param, getNodeName(param)); } } @@ -175,7 +172,7 @@ export default createRule<[Options], MessageIds>({ ...(arrayDestructuring && { ArrayPattern(node): void { if ( - node.parent?.type === AST_NODE_TYPES.RestElement && + node.parent.type === AST_NODE_TYPES.RestElement && node.parent.typeAnnotation ) { return; @@ -185,7 +182,7 @@ export default createRule<[Options], MessageIds>({ !node.typeAnnotation && !isForOfStatementContext(node) && !isAncestorHasTypeAnnotation(node) && - node.parent?.type !== AST_NODE_TYPES.AssignmentExpression + node.parent.type !== AST_NODE_TYPES.AssignmentExpression ) { report(node); } diff --git a/packages/eslint-plugin/src/rules/unbound-method.ts b/packages/eslint-plugin/src/rules/unbound-method.ts index e1c2aed6a019..4d4376b16d89 100644 --- a/packages/eslint-plugin/src/rules/unbound-method.ts +++ b/packages/eslint-plugin/src/rules/unbound-method.ts @@ -272,14 +272,13 @@ function checkMethod( const decl = valueDeclaration as | ts.MethodDeclaration | ts.MethodSignature; - const firstParam = decl.parameters[0]; + const firstParam = decl.parameters.at(0); const firstParamIsThis = firstParam?.name.kind === ts.SyntaxKind.Identifier && // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison - firstParam?.name.escapedText === 'this'; + firstParam.name.escapedText === 'this'; const thisArgIsVoid = - firstParamIsThis && - firstParam?.type?.kind === ts.SyntaxKind.VoidKeyword; + firstParamIsThis && firstParam.type?.kind === ts.SyntaxKind.VoidKeyword; return { dangerous: diff --git a/packages/eslint-plugin/src/rules/unified-signatures.ts b/packages/eslint-plugin/src/rules/unified-signatures.ts index 950125e8686f..6ea6fdc75382 100644 --- a/packages/eslint-plugin/src/rules/unified-signatures.ts +++ b/packages/eslint-plugin/src/rules/unified-signatures.ts @@ -171,7 +171,9 @@ export default createRule({ const isTypeParameter = getIsTypeParameter(typeParameters); for (const overloads of signatures) { forEachPair(overloads, (a, b) => { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const signature0 = (a as MethodDefinition).value ?? a; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const signature1 = (b as MethodDefinition).value ?? b; const unify = compareSignatures( @@ -368,7 +370,7 @@ export default createRule({ } return typeContainsTypeParameter( - (type as TSESTree.TSTypeAnnotation).typeAnnotation || + (type as Partial).typeAnnotation || (type as TSESTree.TSArrayType).elementType, ); } @@ -377,10 +379,7 @@ export default createRule({ function isTSParameterProperty( node: TSESTree.Node, ): node is TSESTree.TSParameterProperty { - return ( - (node as TSESTree.TSParameterProperty).type === - AST_NODE_TYPES.TSParameterProperty - ); + return node.type === AST_NODE_TYPES.TSParameterProperty; } function parametersAreEqual( @@ -492,7 +491,7 @@ export default createRule({ } const scopes: Scope[] = []; - let currentScope: Scope = { + let currentScope: Scope | undefined = { overloads: new Map(), }; @@ -510,11 +509,11 @@ export default createRule({ function checkScope(): void { const failures = checkOverloads( - Array.from(currentScope.overloads.values()), - currentScope.typeParameters, + Array.from(currentScope!.overloads.values()), + currentScope!.typeParameters, ); addFailures(failures); - currentScope = scopes.pop()!; + currentScope = scopes.pop(); } function addOverload( diff --git a/packages/eslint-plugin/src/util/collectUnusedVariables.ts b/packages/eslint-plugin/src/util/collectUnusedVariables.ts index 8ec63de10dc6..943dbff49a18 100644 --- a/packages/eslint-plugin/src/util/collectUnusedVariables.ts +++ b/packages/eslint-plugin/src/util/collectUnusedVariables.ts @@ -246,7 +246,7 @@ class UnusedVarsVisitor< let idOrVariable; if (node.left.type === AST_NODE_TYPES.VariableDeclaration) { - const variable = this.#scopeManager.getDeclaredVariables(node.left)[0]; + const variable = this.#scopeManager.getDeclaredVariables(node.left).at(0); if (!variable) { return; } diff --git a/packages/eslint-plugin/src/util/explicitReturnTypeUtils.ts b/packages/eslint-plugin/src/util/explicitReturnTypeUtils.ts index a47b101e07c5..d767fc834b21 100644 --- a/packages/eslint-plugin/src/util/explicitReturnTypeUtils.ts +++ b/packages/eslint-plugin/src/util/explicitReturnTypeUtils.ts @@ -65,18 +65,12 @@ function isPropertyOfObjectWithType( if (!property || property.type !== AST_NODE_TYPES.Property) { return false; } - const objectExpr = property.parent; // this shouldn't happen, checking just in case - /* istanbul ignore if */ if ( - !objectExpr || - objectExpr.type !== AST_NODE_TYPES.ObjectExpression - ) { + const objectExpr = property.parent; + if (objectExpr.type !== AST_NODE_TYPES.ObjectExpression) { return false; } - const parent = objectExpr.parent; // this shouldn't happen, checking just in case - /* istanbul ignore if */ if (!parent) { - return false; - } + const parent = objectExpr.parent; return ( isTypeAssertion(parent) || @@ -101,11 +95,6 @@ function isPropertyOfObjectWithType( function doesImmediatelyReturnFunctionExpression({ body, }: FunctionNode): boolean { - // Should always have a body; really checking just in case - /* istanbul ignore if */ if (!body) { - return false; - } - // Check if body is a block with a single statement if (body.type === AST_NODE_TYPES.BlockStatement && body.body.length === 1) { const [statement] = body.body; @@ -296,14 +285,14 @@ function checkFunctionExpressionReturnType( function ancestorHasReturnType(node: FunctionNode): boolean { let ancestor: TSESTree.Node | undefined = node.parent; - if (ancestor?.type === AST_NODE_TYPES.Property) { + if (ancestor.type === AST_NODE_TYPES.Property) { ancestor = ancestor.value; } // if the ancestor is not a return, then this function was not returned at all, so we can exit early - const isReturnStatement = ancestor?.type === AST_NODE_TYPES.ReturnStatement; + const isReturnStatement = ancestor.type === AST_NODE_TYPES.ReturnStatement; const isBodylessArrow = - ancestor?.type === AST_NODE_TYPES.ArrowFunctionExpression && + ancestor.type === AST_NODE_TYPES.ArrowFunctionExpression && ancestor.body.type !== AST_NODE_TYPES.BlockStatement; if (!isReturnStatement && !isBodylessArrow) { return false; diff --git a/packages/eslint-plugin/src/util/getStringLength.ts b/packages/eslint-plugin/src/util/getStringLength.ts index 6bec9f4e1adc..32a0087a0a34 100644 --- a/packages/eslint-plugin/src/util/getStringLength.ts +++ b/packages/eslint-plugin/src/util/getStringLength.ts @@ -1,6 +1,6 @@ import Graphemer from 'graphemer'; -let splitter: Graphemer; +let splitter: Graphemer | undefined; function isASCII(value: string): boolean { return /^[\u0020-\u007f]*$/u.test(value); diff --git a/packages/eslint-plugin/src/util/getThisExpression.ts b/packages/eslint-plugin/src/util/getThisExpression.ts index 7a5bcd6ebfd5..9135fe2fdaea 100644 --- a/packages/eslint-plugin/src/util/getThisExpression.ts +++ b/packages/eslint-plugin/src/util/getThisExpression.ts @@ -4,6 +4,7 @@ import { AST_NODE_TYPES } from '@typescript-eslint/utils'; export function getThisExpression( node: TSESTree.Node, ): TSESTree.ThisExpression | undefined { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (node) { if (node.type === AST_NODE_TYPES.CallExpression) { node = node.callee; diff --git a/packages/eslint-plugin/src/util/misc.ts b/packages/eslint-plugin/src/util/misc.ts index ba53a79e37b3..0ac711a3facc 100644 --- a/packages/eslint-plugin/src/util/misc.ts +++ b/packages/eslint-plugin/src/util/misc.ts @@ -168,7 +168,7 @@ function getEnumNames(myEnum: Record): T[] { * Example: ['foo', 'bar', 'baz' ] returns the string "foo, bar, and baz". */ function formatWordList(words: string[]): string { - if (!words?.length) { + if (!words.length) { return ''; } diff --git a/packages/eslint-plugin/tests/util/isNodeEqual.test.ts b/packages/eslint-plugin/tests/util/isNodeEqual.test.ts index a2473fb88dbd..a35599ebceab 100644 --- a/packages/eslint-plugin/tests/util/isNodeEqual.test.ts +++ b/packages/eslint-plugin/tests/util/isNodeEqual.test.ts @@ -24,12 +24,7 @@ const rule = createRule({ return { LogicalExpression: (node: TSESTree.LogicalExpression): void => { - if ( - (node.operator === '??' || - node.operator === '||' || - node.operator === '&&') && - isNodeEqual(node.left, node.right) - ) { + if (isNodeEqual(node.left, node.right)) { context.report({ node, messageId: 'removeExpression', diff --git a/packages/eslint-plugin/tools/generate-configs.ts b/packages/eslint-plugin/tools/generate-configs.ts index ccce38829ef3..85c149c203e4 100644 --- a/packages/eslint-plugin/tools/generate-configs.ts +++ b/packages/eslint-plugin/tools/generate-configs.ts @@ -67,7 +67,7 @@ async function main(): Promise { [ ruleName, typeof rule.meta.docs?.extendsBaseRule === 'string' - ? rule.meta.docs?.extendsBaseRule + ? rule.meta.docs.extendsBaseRule : ruleName, ] as const, ), From 9acf310c16174e12cef74dc0edbc1559fdc774e6 Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Wed, 25 Oct 2023 14:58:52 +0300 Subject: [PATCH 2/2] Removed now-unnecessary disables --- packages/eslint-plugin/src/rules/consistent-type-exports.ts | 1 - packages/eslint-plugin/src/rules/consistent-type-imports.ts | 2 -- packages/eslint-plugin/src/rules/no-extra-parens.ts | 2 +- packages/eslint-plugin/src/rules/no-shadow.ts | 1 - packages/eslint-plugin/src/rules/prefer-readonly.ts | 1 - packages/eslint-plugin/src/rules/return-await.ts | 4 ---- packages/eslint-plugin/src/rules/unified-signatures.ts | 2 -- packages/eslint-plugin/src/util/getThisExpression.ts | 1 - 8 files changed, 1 insertion(+), 13 deletions(-) diff --git a/packages/eslint-plugin/src/rules/consistent-type-exports.ts b/packages/eslint-plugin/src/rules/consistent-type-exports.ts index 450fbe103d4a..2b1768bd9795 100644 --- a/packages/eslint-plugin/src/rules/consistent-type-exports.ts +++ b/packages/eslint-plugin/src/rules/consistent-type-exports.ts @@ -108,7 +108,6 @@ export default createRule({ ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration): void { // Coerce the source into a string for use as a lookup entry. const source = getSourceFromExport(node) ?? 'undefined'; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const sourceExports = (sourceExportsMap[source] ||= { source, reportValueExports: [], diff --git a/packages/eslint-plugin/src/rules/consistent-type-imports.ts b/packages/eslint-plugin/src/rules/consistent-type-imports.ts index 8c821f960882..b880e9a9d92b 100644 --- a/packages/eslint-plugin/src/rules/consistent-type-imports.ts +++ b/packages/eslint-plugin/src/rules/consistent-type-imports.ts @@ -115,7 +115,6 @@ export default createRule({ ImportDeclaration(node): void { const source = node.source.value; // sourceImports is the object containing all the specifics for a particular import source, type or value - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition sourceImportsMap[source] ??= { source, reportValueImports: [], // if there is a mismatch where type importKind but value specifiers @@ -194,7 +193,6 @@ export default createRule({ let parent: TSESTree.Node | undefined = ref.identifier.parent; let child: TSESTree.Node = ref.identifier; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (parent) { switch (parent.type) { // CASE 1: diff --git a/packages/eslint-plugin/src/rules/no-extra-parens.ts b/packages/eslint-plugin/src/rules/no-extra-parens.ts index 180bc4a0b973..ab708faa83db 100644 --- a/packages/eslint-plugin/src/rules/no-extra-parens.ts +++ b/packages/eslint-plugin/src/rules/no-extra-parens.ts @@ -1,5 +1,5 @@ // any is required to work around manipulating the AST in weird ways -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment */ import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; import { AST_NODE_TYPES } from '@typescript-eslint/utils'; diff --git a/packages/eslint-plugin/src/rules/no-shadow.ts b/packages/eslint-plugin/src/rules/no-shadow.ts index 3f6e70018484..5b007b335626 100644 --- a/packages/eslint-plugin/src/rules/no-shadow.ts +++ b/packages/eslint-plugin/src/rules/no-shadow.ts @@ -414,7 +414,6 @@ export default createRule({ let node: TSESTree.Node | undefined = outerDef.name; const location = callExpression.range[1]; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (node) { if (node.type === AST_NODE_TYPES.VariableDeclarator) { if (isInRange(node.init, location)) { diff --git a/packages/eslint-plugin/src/rules/prefer-readonly.ts b/packages/eslint-plugin/src/rules/prefer-readonly.ts index 7d5591b11680..b9980536fb23 100644 --- a/packages/eslint-plugin/src/rules/prefer-readonly.ts +++ b/packages/eslint-plugin/src/rules/prefer-readonly.ts @@ -106,7 +106,6 @@ export default createRule({ ): boolean { let current: ts.Node = node.parent; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (current) { const parent = current.parent; diff --git a/packages/eslint-plugin/src/rules/return-await.ts b/packages/eslint-plugin/src/rules/return-await.ts index ab8f09b417ab..5bb2ee19b6bc 100644 --- a/packages/eslint-plugin/src/rules/return-await.ts +++ b/packages/eslint-plugin/src/rules/return-await.ts @@ -72,7 +72,6 @@ export default createRule({ function inTry(node: ts.Node): boolean { let ancestor = node.parent; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if (ts.isTryStatement(ancestor)) { return true; @@ -87,7 +86,6 @@ export default createRule({ function inCatch(node: ts.Node): boolean { let ancestor = node.parent; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if (ts.isCatchClause(ancestor)) { return true; @@ -102,7 +100,6 @@ export default createRule({ function isReturnPromiseInFinally(node: ts.Node): boolean { let ancestor = node.parent; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if ( ts.isTryStatement(ancestor.parent) && @@ -120,7 +117,6 @@ export default createRule({ function hasFinallyBlock(node: ts.Node): boolean { let ancestor = node.parent; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (ancestor && !ts.isFunctionLike(ancestor)) { if (ts.isTryStatement(ancestor)) { return !!ancestor.finallyBlock; diff --git a/packages/eslint-plugin/src/rules/unified-signatures.ts b/packages/eslint-plugin/src/rules/unified-signatures.ts index 6ea6fdc75382..17c1d8ff46fc 100644 --- a/packages/eslint-plugin/src/rules/unified-signatures.ts +++ b/packages/eslint-plugin/src/rules/unified-signatures.ts @@ -171,9 +171,7 @@ export default createRule({ const isTypeParameter = getIsTypeParameter(typeParameters); for (const overloads of signatures) { forEachPair(overloads, (a, b) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const signature0 = (a as MethodDefinition).value ?? a; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const signature1 = (b as MethodDefinition).value ?? b; const unify = compareSignatures( diff --git a/packages/eslint-plugin/src/util/getThisExpression.ts b/packages/eslint-plugin/src/util/getThisExpression.ts index 9135fe2fdaea..7a5bcd6ebfd5 100644 --- a/packages/eslint-plugin/src/util/getThisExpression.ts +++ b/packages/eslint-plugin/src/util/getThisExpression.ts @@ -4,7 +4,6 @@ import { AST_NODE_TYPES } from '@typescript-eslint/utils'; export function getThisExpression( node: TSESTree.Node, ): TSESTree.ThisExpression | undefined { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (node) { if (node.type === AST_NODE_TYPES.CallExpression) { node = node.callee;