From 62119ec9ccf2cb7620046e1e6922fb1788b5290e Mon Sep 17 00:00:00 2001 From: Alexander T Date: Wed, 19 Jun 2019 18:45:02 +0300 Subject: [PATCH] @typescript-eslint/no-unnecessary-type-assertion --- .eslintrc | 2 +- scripts/buildProtocol.ts | 2 +- src/compiler/checker.ts | 22 ++++++++++---------- src/compiler/emitter.ts | 4 ++-- src/compiler/transformers/generators.ts | 8 +++---- src/compiler/transformers/module/system.ts | 2 +- src/compiler/transformers/ts.ts | 4 ++-- src/compiler/utilities.ts | 4 ++-- src/compiler/visitor.ts | 8 +++---- src/harness/harness.ts | 2 +- src/server/editorServices.ts | 2 +- src/services/codefixes/convertToEs6Module.ts | 4 +++- src/services/documentHighlights.ts | 14 ++++++------- src/services/refactors/extractSymbol.ts | 2 +- src/testRunner/compilerRunner.ts | 4 ++-- src/testRunner/unittests/tscWatch/helpers.ts | 2 +- 16 files changed, 44 insertions(+), 42 deletions(-) diff --git a/.eslintrc b/.eslintrc index 622bf38c08a..3f7af19676e 100644 --- a/.eslintrc +++ b/.eslintrc @@ -38,7 +38,7 @@ "@typescript-eslint/no-this-alias": "error", "@typescript-eslint/no-triple-slash-reference": "off", "@typescript-eslint/no-unnecessary-qualifier": "error", - "@typescript-eslint/no-unnecessary-type-assertion": "off", + "@typescript-eslint/no-unnecessary-type-assertion": "error", "@typescript-eslint/no-use-before-define": "off", "@typescript-eslint/no-var-requires": "off", "@typescript-eslint/prefer-for-of": "error", diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts index b352acba12f..a245bf4d8e8 100644 --- a/scripts/buildProtocol.ts +++ b/scripts/buildProtocol.ts @@ -30,7 +30,7 @@ class DeclarationsWalker { text += "\ndeclare namespace ts {\n"; text += " // these types are empty stubs for types from services and should not be used directly\n"; for (const type of walker.removedTypes) { - text += ` export type ${type.symbol!.name} = never;\n`; + text += ` export type ${type.symbol.name} = never;\n`; } text += "}"; } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a4ad3af7d9a..2ed08f6c3f4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4093,7 +4093,7 @@ namespace ts { let typeParameters: TypeParameterDeclaration[] | undefined; let typeArguments: TypeNode[] | undefined; if (context.flags & NodeBuilderFlags.WriteTypeArgumentsOfSignature && signature.target && signature.mapper && signature.target.typeParameters) { - typeArguments = signature.target.typeParameters.map(parameter => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper!), context)); + typeArguments = signature.target.typeParameters.map(parameter => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context)); } else { typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter, context)); @@ -5893,7 +5893,7 @@ namespace ts { if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return links.type = errorType; } - let type = instantiateType(getTypeOfSymbol(links.target!), links.mapper!); + let type = instantiateType(getTypeOfSymbol(links.target!), links.mapper); if (!popTypeResolution()) { type = reportCircularityError(symbol); } @@ -7006,7 +7006,7 @@ namespace ts { const minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); const typeParamCount = length(baseSig.typeParameters); if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { - const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)!) : cloneSignature(baseSig); + const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -7903,7 +7903,7 @@ namespace ts { if (!typeParameter.default) { if (typeParameter.target) { const targetDefault = getResolvedTypeParameterDefault(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper!) : noConstraintType; + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { // To block recursion, set the initial value to the resolvingDefaultType. @@ -8563,7 +8563,7 @@ namespace ts { if (!pushTypeResolution(signature, TypeSystemPropertyName.ResolvedReturnType)) { return errorType; } - let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper!) : + let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), UnionReduction.Subtype) : getReturnTypeFromAnnotation(signature.declaration!) || isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration!)) || @@ -8815,7 +8815,7 @@ namespace ts { if (!typeParameter.constraint) { if (typeParameter.target) { const targetConstraint = getConstraintOfTypeParameter(typeParameter.target); - typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper!) : noConstraintType; + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { const constraintDeclaration = getConstraintDeclaration(typeParameter); @@ -11175,7 +11175,7 @@ namespace ts { // type mappers. This ensures that original type identities are properly preserved and that aliases // always reference a non-aliases. symbol = links.target!; - mapper = combineTypeMappers(links.mapper!, mapper); + mapper = combineTypeMappers(links.mapper, mapper); } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. @@ -11232,7 +11232,7 @@ namespace ts { // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. - const combinedMapper = type.objectFlags & ObjectFlags.Instantiated ? combineTypeMappers(type.mapper!, mapper) : mapper; + const combinedMapper = type.objectFlags & ObjectFlags.Instantiated ? combineTypeMappers(type.mapper, mapper) : mapper; const typeArguments: Type[] = map(typeParameters, combinedMapper); const id = getTypeListId(typeArguments); let result = links.instantiations!.get(id); @@ -18951,7 +18951,7 @@ namespace ts { return createTypeReference((declaredManagedType as GenericType), args); } else if (length(declaredManagedType.aliasTypeArguments) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJSFile(context)); + const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol!, args); } } @@ -25194,7 +25194,7 @@ namespace ts { } result = result && checkTypeAssignableTo( typeArguments[i], - instantiateType(constraint, mapper!), + instantiateType(constraint, mapper), node.typeArguments![i], Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } @@ -25486,7 +25486,7 @@ namespace ts { return; } else if (nodeIsPresent((subsequentNode).body)) { - error(errorNode, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name!)); + error(errorNode, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name)); return; } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index ddd273c3602..019f1f56872 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2661,7 +2661,7 @@ namespace ts { writeKeyword("function"); emit(node.asteriskToken); writeSpace(); - emitIdentifierName(node.name!); // TODO: GH#18217 + emitIdentifierName(node.name); // TODO: GH#18217 emitSignatureAndBody(node, emitSignatureHead); } @@ -3490,7 +3490,7 @@ namespace ts { if (shouldEmitPrologueDirective) { if (needsToSetSourceFile) { needsToSetSourceFile = false; - setSourceFile(sourceFile!); + setSourceFile(sourceFile); } writeLine(); const pos = writer.getTextPos(); diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index aa397ee662d..8423aa252f1 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -936,7 +936,7 @@ namespace ts { // x = %sent%; const resumeLabel = defineLabel(); - const expression = visitNode(node.expression!, visitor, isExpression); + const expression = visitNode(node.expression, visitor, isExpression); if (node.asteriskToken) { const iterator = (getEmitFlags(node.expression!) & EmitFlags.Iterator) === 0 ? createValuesHelper(context, expression, /*location*/ node) @@ -1262,7 +1262,7 @@ namespace ts { while (variablesWritten < numVariables) { for (let i = variablesWritten; i < numVariables; i++) { const variable = variables[i]; - if (containsYield(variable.initializer!) && pendingExpressions.length > 0) { + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { break; } @@ -1283,7 +1283,7 @@ namespace ts { return setSourceMapRange( createAssignment( setSourceMapRange(getSynthesizedClone(node.name), node.name), - visitNode(node.initializer!, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression) ), node ); @@ -1868,7 +1868,7 @@ namespace ts { function transformAndEmitThrowStatement(node: ThrowStatement): void { emitThrow( - visitNode(node.expression!, visitor, isExpression), + visitNode(node.expression, visitor, isExpression), /*location*/ node ); } diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index ae303440bc1..c48d07312dd 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -621,7 +621,7 @@ namespace ts { if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id]!, node); + deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); } else { statements = appendExportsOfImportEqualsDeclaration(statements, node); diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index a70fb820e79..ee366eac249 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1271,7 +1271,7 @@ namespace ts { const propertyName = isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) ? updateComputedPropertyName(property.name, getGeneratedNameForNode(property.name)) : property.name; - const initializer = visitNode(property.initializer!, visitor, isExpression); + const initializer = visitNode(property.initializer, visitor, isExpression); const memberAccess = createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); return createAssignment(memberAccess, initializer); @@ -2477,7 +2477,7 @@ namespace ts { return setTextRange( createAssignment( getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), - visitNode(node.initializer!, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression) ), /*location*/ node ); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 3a195277e0d..b1ceee7979c 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2201,13 +2201,13 @@ namespace ts { let result: (JSDoc | JSDocTag)[] | undefined; // Pull parameter comments from declaring function as well if (isVariableLike(hostNode) && hasInitializer(hostNode) && hasJSDocNodes(hostNode.initializer!)) { - result = addRange(result, (hostNode.initializer as HasJSDoc).jsDoc!); + result = addRange(result, (hostNode.initializer as HasJSDoc).jsDoc); } let node: Node | undefined = hostNode; while (node && node.parent) { if (hasJSDocNodes(node)) { - result = addRange(result, node.jsDoc!); + result = addRange(result, node.jsDoc); } if (node.kind === SyntaxKind.Parameter) { diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 53ccd81f7a6..afc03e5b4be 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -334,7 +334,7 @@ namespace ts { nodesVisitor((node).decorators, visitor, isDecorator), nodesVisitor((node).modifiers, visitor, isModifier), nodesVisitor((node).parameters, visitor, isParameterDeclaration), - visitNode((node).type!, visitor, isTypeNode)); + visitNode((node).type, visitor, isTypeNode)); // Types @@ -564,7 +564,7 @@ namespace ts { case SyntaxKind.YieldExpression: return updateYield(node, visitNode((node).asteriskToken, tokenVisitor, isToken), - visitNode((node).expression!, visitor, isExpression)); + visitNode((node).expression, visitor, isExpression)); case SyntaxKind.SpreadElement: return updateSpread(node, @@ -683,7 +683,7 @@ namespace ts { case SyntaxKind.ThrowStatement: return updateThrow(node, - visitNode((node).expression!, visitor, isExpression)); + visitNode((node).expression, visitor, isExpression)); case SyntaxKind.TryStatement: return updateTry(node, @@ -857,7 +857,7 @@ namespace ts { case SyntaxKind.JsxAttribute: return updateJsxAttribute(node, visitNode((node).name, visitor, isIdentifier), - visitNode((node).initializer!, visitor, isStringLiteralOrJsxExpression)); + visitNode((node).initializer, visitor, isStringLiteralOrJsxExpression)); case SyntaxKind.JsxAttributes: return updateJsxAttributes(node, diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 065117db3dd..d544eec51e3 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -833,7 +833,7 @@ namespace Harness { setCompilerOptionsFromHarnessSetting(harnessSettings, options); } if (options.rootDirs) { - options.rootDirs = ts.map(options.rootDirs, d => ts.getNormalizedAbsolutePath(d, currentDirectory!)); + options.rootDirs = ts.map(options.rootDirs, d => ts.getNormalizedAbsolutePath(d, currentDirectory)); } const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : true; diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 4e5435feaba..219b9dce885 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1784,7 +1784,7 @@ namespace ts.server { } project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); - this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition!, parsedCommandLine.compileOnSave!); // TODO: GH#18217 + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition!, parsedCommandLine.compileOnSave); // TODO: GH#18217 } private updateNonInferredProjectFiles(project: ExternalProject | ConfiguredProject, files: T[], propertyReader: FilePropertyReader) { diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index 65ea757d060..fd756430e49 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -355,7 +355,9 @@ namespace ts.codefix { const importSpecifiers = mapAllOrFail(name.elements, e => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? undefined - : makeImportSpecifier(e.propertyName && (e.propertyName as Identifier).text, e.name.text)); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) + // (TODO: GH#18217) + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + : makeImportSpecifier(e.propertyName && (e.propertyName as Identifier).text, e.name.text)); if (importSpecifiers) { return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; } diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index f0f3c165d7e..1f11b0f52d5 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -244,7 +244,7 @@ namespace ts.DocumentHighlights { function getLoopBreakContinueOccurrences(loopNode: IterationStatement): Node[] { const keywords: Node[] = []; - if (pushKeywordIf(keywords, loopNode.getFirstToken()!, SyntaxKind.ForKeyword, SyntaxKind.WhileKeyword, SyntaxKind.DoKeyword)) { + if (pushKeywordIf(keywords, loopNode.getFirstToken(), SyntaxKind.ForKeyword, SyntaxKind.WhileKeyword, SyntaxKind.DoKeyword)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. if (loopNode.kind === SyntaxKind.DoStatement) { const loopTokens = loopNode.getChildren(); @@ -259,7 +259,7 @@ namespace ts.DocumentHighlights { forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), statement => { if (ownsBreakOrContinueStatement(loopNode, statement)) { - pushKeywordIf(keywords, statement.getFirstToken()!, SyntaxKind.BreakKeyword, SyntaxKind.ContinueKeyword); + pushKeywordIf(keywords, statement.getFirstToken(), SyntaxKind.BreakKeyword, SyntaxKind.ContinueKeyword); } }); @@ -289,15 +289,15 @@ namespace ts.DocumentHighlights { function getSwitchCaseDefaultOccurrences(switchStatement: SwitchStatement): Node[] { const keywords: Node[] = []; - pushKeywordIf(keywords, switchStatement.getFirstToken()!, SyntaxKind.SwitchKeyword); + pushKeywordIf(keywords, switchStatement.getFirstToken(), SyntaxKind.SwitchKeyword); // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. forEach(switchStatement.caseBlock.clauses, clause => { - pushKeywordIf(keywords, clause.getFirstToken()!, SyntaxKind.CaseKeyword, SyntaxKind.DefaultKeyword); + pushKeywordIf(keywords, clause.getFirstToken(), SyntaxKind.CaseKeyword, SyntaxKind.DefaultKeyword); forEach(aggregateAllBreakAndContinueStatements(clause), statement => { if (ownsBreakOrContinueStatement(switchStatement, statement)) { - pushKeywordIf(keywords, statement.getFirstToken()!, SyntaxKind.BreakKeyword); + pushKeywordIf(keywords, statement.getFirstToken(), SyntaxKind.BreakKeyword); } }); }); @@ -308,10 +308,10 @@ namespace ts.DocumentHighlights { function getTryCatchFinallyOccurrences(tryStatement: TryStatement, sourceFile: SourceFile): Node[] { const keywords: Node[] = []; - pushKeywordIf(keywords, tryStatement.getFirstToken()!, SyntaxKind.TryKeyword); + pushKeywordIf(keywords, tryStatement.getFirstToken(), SyntaxKind.TryKeyword); if (tryStatement.catchClause) { - pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken()!, SyntaxKind.CatchKeyword); + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), SyntaxKind.CatchKeyword); } if (tryStatement.finallyBlock) { diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 823bd640a59..c55acb33e1d 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -1193,7 +1193,7 @@ namespace ts.refactor.extractSymbol { if (!returnValueProperty) { returnValueProperty = "__return"; } - assignments.unshift(createPropertyAssignment(returnValueProperty, visitNode((node).expression!, visitor))); + assignments.unshift(createPropertyAssignment(returnValueProperty, visitNode((node).expression, visitor))); } if (assignments.length === 1) { return createReturn(assignments[0].name as Expression); diff --git a/src/testRunner/compilerRunner.ts b/src/testRunner/compilerRunner.ts index 76c7c728aa1..0197188e822 100644 --- a/src/testRunner/compilerRunner.ts +++ b/src/testRunner/compilerRunner.ts @@ -145,7 +145,7 @@ class CompilerTest { assert.equal(testCaseContent.tsConfig.fileNames.length, 0, `list of files in tsconfig is not currently supported`); tsConfigOptions = ts.cloneCompilerOptions(testCaseContent.tsConfig.options); - this.tsConfigFiles.push(this.createHarnessTestFile(testCaseContent.tsConfigFileUnitData!, rootDir, ts.combinePaths(rootDir, tsConfigOptions.configFilePath!))); + this.tsConfigFiles.push(this.createHarnessTestFile(testCaseContent.tsConfigFileUnitData!, rootDir, ts.combinePaths(rootDir, tsConfigOptions.configFilePath))); } else { const baseUrl = this.harnessSettings.baseUrl; @@ -276,4 +276,4 @@ class CompilerTest { private createHarnessTestFile(lastUnit: Harness.TestCaseParser.TestUnitData, rootDir: string, unitName?: string): Harness.Compiler.TestFile { return { unitName: unitName || this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content, fileOptions: lastUnit.fileOptions }; } -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/tscWatch/helpers.ts b/src/testRunner/unittests/tscWatch/helpers.ts index f8647393cb1..bee3949708e 100644 --- a/src/testRunner/unittests/tscWatch/helpers.ts +++ b/src/testRunner/unittests/tscWatch/helpers.ts @@ -214,7 +214,7 @@ namespace ts.tscWatch { } export function getDiagnosticOfFileFromProgram(program: Program, filePath: string, start: number, length: number, message: DiagnosticMessage | DiagnosticMessageChain, ...args: (string | number)[]): Diagnostic { - return getDiagnosticOfFileFrom(program.getSourceFileByPath(toPath(filePath, program.getCurrentDirectory(), s => s.toLowerCase()))!, + return getDiagnosticOfFileFrom(program.getSourceFileByPath(toPath(filePath, program.getCurrentDirectory(), s => s.toLowerCase())), start, length, message, ...args); }