From 4dd0d07ccec1f4375bf4284fe2be1a9ad78d6fbe Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 15 Feb 2018 14:49:50 -0800 Subject: [PATCH 1/4] Apply 'no-unnecessary-type-assertion' lint rule --- Gulpfile.ts | 14 +- Jakefile.js | 16 +- scripts/tslint/rules/booleanTriviaRule.ts | 4 +- .../rules/noUnnecessaryTypeAssertion2Rule.ts | 98 +++++ scripts/tslint/tsconfig.json | 1 + src/compiler/binder.ts | 27 +- src/compiler/builder.ts | 2 +- src/compiler/checker.ts | 336 +++++++++--------- src/compiler/declarationEmitter.ts | 36 +- src/compiler/emitter.ts | 12 +- src/compiler/factory.ts | 50 +-- src/compiler/parser.ts | 16 +- src/compiler/program.ts | 2 +- src/compiler/transformers/es2015.ts | 20 +- src/compiler/transformers/es2017.ts | 2 +- src/compiler/transformers/esnext.ts | 5 +- src/compiler/transformers/generators.ts | 7 +- src/compiler/transformers/jsx.ts | 20 +- src/compiler/transformers/module/module.ts | 2 +- src/compiler/transformers/module/system.ts | 11 +- src/compiler/transformers/ts.ts | 22 +- src/compiler/utilities.ts | 62 ++-- src/harness/fourslash.ts | 16 +- src/harness/harness.ts | 7 +- src/harness/harnessLanguageService.ts | 2 +- .../unittests/reuseProgramStructure.ts | 2 +- src/harness/unittests/textChanges.ts | 2 +- .../unittests/tsserverProjectSystem.ts | 2 +- src/harness/virtualFileSystem.ts | 13 +- src/server/editorServices.ts | 2 +- src/server/scriptVersionCache.ts | 6 +- src/services/breakpoints.ts | 9 +- src/services/codefixes/fixUnusedIdentifier.ts | 6 +- src/services/codefixes/helpers.ts | 2 +- src/services/codefixes/inferFromUsage.ts | 4 +- src/services/completions.ts | 12 +- src/services/findAllReferences.ts | 10 +- src/services/formatting/formatting.ts | 2 +- src/services/formatting/smartIndenter.ts | 5 +- src/services/importTracker.ts | 2 +- src/services/jsDoc.ts | 4 +- src/services/navigateTo.ts | 6 +- src/services/navigationBar.ts | 8 +- .../refactors/annotateWithTypeFromJSDoc.ts | 2 +- .../refactors/convertFunctionToEs6Class.ts | 3 +- src/services/refactors/convertToEs6Module.ts | 14 +- src/services/refactors/extractSymbol.ts | 10 +- src/services/services.ts | 8 +- src/services/signatureHelp.ts | 15 +- src/services/symbolDisplay.ts | 4 +- src/services/utilities.ts | 2 +- tslint.json | 2 + 52 files changed, 496 insertions(+), 451 deletions(-) create mode 100644 scripts/tslint/rules/noUnnecessaryTypeAssertion2Rule.ts diff --git a/Gulpfile.ts b/Gulpfile.ts index 7222c9bcd6aff..7633d4969671a 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -53,7 +53,6 @@ const cmdLineOptions = minimist(process.argv.slice(2), { "ru": "runners", "runner": "runners", "r": "reporter", "c": "colors", "color": "colors", - "f": "files", "file": "files", "w": "workers", }, default: { @@ -69,7 +68,6 @@ const cmdLineOptions = minimist(process.argv.slice(2), { light: process.env.light === undefined || process.env.light !== "false", reporter: process.env.reporter || process.env.r, lint: process.env.lint || true, - files: process.env.f || process.env.file || process.env.files || "", workers: process.env.workerCount || os.cpus().length, } }); @@ -1112,13 +1110,11 @@ function spawnLintWorker(files: {path: string}[], callback: (failures: number) = gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => { if (fold.isTravis()) console.log(fold.start("lint")); - const fileMatcher = cmdLineOptions.files; - const files = fileMatcher - ? `src/**/${fileMatcher}` - : `Gulpfile.ts "scripts/generateLocalizedDiagnosticMessages.ts" "scripts/tslint/**/*.ts" "src/**/*.ts" --exclude "src/lib/*.d.ts"`; - const cmd = `node node_modules/tslint/bin/tslint ${files} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`; - console.log("Linting: " + cmd); - child_process.execSync(cmd, { stdio: [0, 1, 2] }); + for (const project of ["scripts/tslint/tsconfig.json", "src/tsconfig-base.json"]) { + const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters`; + console.log("Linting: " + cmd); + child_process.execSync(cmd, { stdio: [0, 1, 2] }); + } if (fold.isTravis()) console.log(fold.end("lint")); }); diff --git a/Jakefile.js b/Jakefile.js index d676926abac8d..13da0d9918587 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -1302,15 +1302,13 @@ function spawnLintWorker(files, callback) { desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex"); task("lint", ["build-rules"], () => { if (fold.isTravis()) console.log(fold.start("lint")); - const fileMatcher = process.env.f || process.env.file || process.env.files; - - const files = fileMatcher - ? `src/**/${fileMatcher}` - : `Gulpfile.ts scripts/generateLocalizedDiagnosticMessages.ts "scripts/tslint/**/*.ts" "src/**/*.ts" --exclude "src/lib/*.d.ts"`; - const cmd = `node node_modules/tslint/bin/tslint ${files} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`; - console.log("Linting: " + cmd); - jake.exec([cmd], { interactive: true, windowsVerbatimArguments: true }, () => { + function lint(project, cb) { + const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters`; + console.log("Linting: " + cmd); + jake.exec([cmd], { interactive: true, windowsVerbatimArguments: true }, cb); + } + lint("scripts/tslint/tsconfig.json", () => lint("src/tsconfig-base.json", () => { if (fold.isTravis()) console.log(fold.end("lint")); complete(); - }); + })); }); diff --git a/scripts/tslint/rules/booleanTriviaRule.ts b/scripts/tslint/rules/booleanTriviaRule.ts index c498131be16d2..dbfdc28438e23 100644 --- a/scripts/tslint/rules/booleanTriviaRule.ts +++ b/scripts/tslint/rules/booleanTriviaRule.ts @@ -27,7 +27,7 @@ function walk(ctx: Lint.WalkContext): void { /** Skip certain function/method names whose parameter names are not informative. */ function shouldIgnoreCalledExpression(expression: ts.Expression): boolean { if (expression.kind === ts.SyntaxKind.PropertyAccessExpression) { - const methodName = (expression as ts.PropertyAccessExpression).name.text as string; + const methodName = (expression as ts.PropertyAccessExpression).name.text; if (methodName.indexOf("set") === 0) { return true; } @@ -45,7 +45,7 @@ function walk(ctx: Lint.WalkContext): void { } } else if (expression.kind === ts.SyntaxKind.Identifier) { - const functionName = (expression as ts.Identifier).text as string; + const functionName = (expression as ts.Identifier).text; if (functionName.indexOf("set") === 0) { return true; } diff --git a/scripts/tslint/rules/noUnnecessaryTypeAssertion2Rule.ts b/scripts/tslint/rules/noUnnecessaryTypeAssertion2Rule.ts new file mode 100644 index 0000000000000..bcfb91b739fb4 --- /dev/null +++ b/scripts/tslint/rules/noUnnecessaryTypeAssertion2Rule.ts @@ -0,0 +1,98 @@ +/** + * @license + * Copyright 2016 Palantir Technologies, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as ts from "typescript"; +import * as Lint from "tslint"; + +export class Rule extends Lint.Rules.TypedRule { + /* tslint:disable:object-literal-sort-keys */ + public static metadata: Lint.IRuleMetadata = { + ruleName: "no-unnecessary-type-assertion", + description: "Warns if a type assertion does not change the type of an expression.", + options: { + type: "list", + listType: { + type: "array", + items: { type: "string" }, + }, + }, + optionsDescription: "A list of whitelisted assertion types to ignore", + type: "typescript", + hasFix: true, + typescriptOnly: true, + requiresTypeInfo: true, + }; + /* tslint:enable:object-literal-sort-keys */ + + public static FAILURE_STRING = "This assertion is unnecessary since it does not change the type of the expression."; + + public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { + return this.applyWithWalker(new Walker(sourceFile, this.ruleName, this.ruleArguments, program.getTypeChecker())); + } +} + +class Walker extends Lint.AbstractWalker { + constructor(sourceFile: ts.SourceFile, ruleName: string, options: string[], private readonly checker: ts.TypeChecker) { + super(sourceFile, ruleName, options); + } + + public walk(sourceFile: ts.SourceFile) { + const cb = (node: ts.Node): void => { + switch (node.kind) { + case ts.SyntaxKind.TypeAssertionExpression: + case ts.SyntaxKind.AsExpression: + this.verifyCast(node as ts.TypeAssertion | ts.AsExpression); + } + + return ts.forEachChild(node, cb); + }; + + return ts.forEachChild(sourceFile, cb); + } + + private verifyCast(node: ts.TypeAssertion | ts.NonNullExpression | ts.AsExpression) { + if (ts.isAssertionExpression(node) && this.options.indexOf(node.type.getText(this.sourceFile)) !== -1) { + return; + } + const castType = this.checker.getTypeAtLocation(node); + if (castType === undefined) { + return; + } + + if (node.kind !== ts.SyntaxKind.NonNullExpression && + (castType.flags & ts.TypeFlags.Literal || + castType.flags & ts.TypeFlags.Object && + (castType as ts.ObjectType).objectFlags & ts.ObjectFlags.Tuple) || + // Sometimes tuple types don't have ObjectFlags.Tuple set, like when + // they're being matched against an inferred type. So, in addition, + // check if any properties are numbers, which implies that this is + // likely a tuple type. + (castType.getProperties().some((symbol) => !isNaN(Number(symbol.name))))) { + + // It's not always safe to remove a cast to a literal type or tuple + // type, as those types are sometimes widened without the cast. + return; + } + + const uncastType = this.checker.getTypeAtLocation(node.expression); + if (uncastType === castType) { + this.addFailureAtNode(node, Rule.FAILURE_STRING, node.kind === ts.SyntaxKind.TypeAssertionExpression + ? Lint.Replacement.deleteFromTo(node.getStart(), node.expression.getStart()) + : Lint.Replacement.deleteFromTo(node.expression.getEnd(), node.getEnd())); + } + } +} diff --git a/scripts/tslint/tsconfig.json b/scripts/tslint/tsconfig.json index c9bf8dc01dc6a..cdb63febcc758 100644 --- a/scripts/tslint/tsconfig.json +++ b/scripts/tslint/tsconfig.json @@ -1,5 +1,6 @@ { "compilerOptions": { + "lib": "es6", "noImplicitAny": true, "noImplicitReturns": true, "noImplicitThis": true, diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 05edda7cd3c52..06b15c7718daf 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -264,7 +264,7 @@ namespace ts { return (isGlobalScopeAugmentation(node) ? "__global" : `"${moduleName}"`) as __String; } if (name.kind === SyntaxKind.ComputedPropertyName) { - const nameExpression = (name).expression; + const nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (isStringOrNumericLiteral(nameExpression)) { return escapeLeadingUnderscores(nameExpression.text); @@ -459,10 +459,7 @@ namespace ts { // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (node.kind === SyntaxKind.JSDocTypedefTag) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag && - (node as JSDocTypedefTag).name && - (node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier && - ((node as JSDocTypedefTag).name as Identifier).isInJSDocNamespace; + const isJSDocTypedefInJSDocNamespace = isJSDocTypedefTag(node) && node.name && node.name.kind === SyntaxKind.Identifier && node.name.isInJSDocNamespace; if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefInJSDocNamespace) { const exportKind = symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0; const local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); @@ -527,7 +524,7 @@ namespace ts { if (!isIIFE) { currentFlow = { flags: FlowFlags.Start }; if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) { - (currentFlow).container = node; + currentFlow.container = node; } } // We create a return control flow graph for IIFEs and constructors. For constructors @@ -997,7 +994,7 @@ namespace ts { addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); if (node.initializer.kind !== SyntaxKind.VariableDeclarationList) { - bindAssignmentTargetFlow(node.initializer); + bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); addAntecedent(preLoopLabel, currentFlow); @@ -1170,7 +1167,7 @@ namespace ts { i++; } const preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); const clause = clauses[i]; @@ -1251,13 +1248,13 @@ namespace ts { else if (node.kind === SyntaxKind.ObjectLiteralExpression) { for (const p of (node).properties) { if (p.kind === SyntaxKind.PropertyAssignment) { - bindDestructuringTargetFlow((p).initializer); + bindDestructuringTargetFlow(p.initializer); } else if (p.kind === SyntaxKind.ShorthandPropertyAssignment) { - bindAssignmentTargetFlow((p).name); + bindAssignmentTargetFlow(p.name); } else if (p.kind === SyntaxKind.SpreadAssignment) { - bindAssignmentTargetFlow((p).expression); + bindAssignmentTargetFlow(p.expression); } } } @@ -1572,7 +1569,7 @@ namespace ts { } function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean { - const body = node.kind === SyntaxKind.SourceFile ? node : (node).body; + const body = node.kind === SyntaxKind.SourceFile ? node : node.body; if (body && (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock)) { for (const stat of (body).statements) { if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) { @@ -2210,7 +2207,7 @@ namespace ts { function checkTypePredicate(node: TypePredicateNode) { const { parameterName, type } = node; if (parameterName && parameterName.kind === SyntaxKind.Identifier) { - checkStrictModeIdentifier(parameterName as Identifier); + checkStrictModeIdentifier(parameterName); } if (parameterName && parameterName.kind === SyntaxKind.ThisType) { seenThisKeyword = true; @@ -2555,13 +2552,13 @@ namespace ts { } } - checkStrictModeFunctionName(node); + checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); bindBlockScopedDeclaration(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); } else { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); + declareSymbolAndAddToSymbolTable(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); } } diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 121609db104d2..c2f816a4c7167 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -228,7 +228,7 @@ namespace ts { host = oldProgramOrHost as CompilerHost; } else { - newProgram = newProgramOrRootNames as Program; + newProgram = newProgramOrRootNames; host = hostOrOptions as BuilderProgramHost; oldProgram = oldProgramOrHost as BuilderProgram; } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b817d9b965afa..654a85dafef3b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1269,7 +1269,7 @@ namespace ts { // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. if (isClassLike(location.parent) && !hasModifier(location, ModifierFlags.Static)) { - const ctor = findConstructorDeclaration(location.parent); + const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & SymbolFlags.Value)) { // Remember the property node, it will be used later to report appropriate error @@ -1680,7 +1680,7 @@ namespace ts { if (node.moduleReference.kind === SyntaxKind.ExternalModuleReference) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, getExternalModuleImportEqualsDeclarationExpression(node))); } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } function resolveExportByName(moduleSymbol: Symbol, name: __String, dontResolveAlias: boolean) { @@ -1721,7 +1721,7 @@ namespace ts { } function getTargetOfImportClause(node: ImportClause, dontResolveAlias: boolean): Symbol { - const moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); + const moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { let exportDefaultSymbol: Symbol; @@ -1746,7 +1746,7 @@ namespace ts { } function getTargetOfNamespaceImport(node: NamespaceImport, dontResolveAlias: boolean): Symbol { - const moduleSpecifier = (node.parent.parent).moduleSpecifier; + const moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); } @@ -1836,7 +1836,7 @@ namespace ts { } function getTargetOfImportSpecifier(node: ImportSpecifier, dontResolveAlias: boolean): Symbol { - return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); } function getTargetOfNamespaceExportDeclaration(node: NamespaceExportDeclaration, dontResolveAlias: boolean): Symbol { @@ -1937,7 +1937,7 @@ namespace ts { } else if (isInternalModuleImportEqualsDeclaration(node)) { // import foo = - checkExpressionCached((node).moduleReference); + checkExpressionCached(node.moduleReference); } } } @@ -1990,7 +1990,7 @@ namespace ts { let left: EntityNameOrEntityNameExpression; if (name.kind === SyntaxKind.QualifiedName) { - left = (name).left; + left = name.left; } else if (name.kind === SyntaxKind.PropertyAccessExpression) { left = name.expression; @@ -3040,7 +3040,7 @@ namespace ts { function createTypeNodeFromObjectType(type: ObjectType): TypeNode { if (isGenericMappedType(type)) { - return createMappedTypeNodeFromType(type); + return createMappedTypeNodeFromType(type); } const resolved = resolveStructuredTypeMembers(type); @@ -3130,7 +3130,7 @@ namespace ts { const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); const typeArgumentNodes = typeArgumentSlice && createNodeArray(typeArgumentSlice); const namePart = symbolToTypeReferenceName(parent); - (namePart.kind === SyntaxKind.Identifier ? namePart : namePart.right).typeArguments = typeArgumentNodes; + (namePart.kind === SyntaxKind.Identifier ? namePart : namePart.right).typeArguments = typeArgumentNodes; if (qualifiedName) { Debug.assert(!qualifiedName.right); @@ -3162,7 +3162,7 @@ namespace ts { } if (typeArgumentNodes) { - const lastIdentifier = entityName.kind === SyntaxKind.Identifier ? entityName : entityName.right; + const lastIdentifier = entityName.kind === SyntaxKind.Identifier ? entityName : entityName.right; lastIdentifier.typeArguments = undefined; } @@ -3183,7 +3183,7 @@ namespace ts { rightPart = rightPart.left; } - left.right = rightPart.left; + left.right = rightPart.left; rightPart.left = left; return right; } @@ -3318,7 +3318,7 @@ namespace ts { const typePredicate = getTypePredicateOfSignature(signature); if (typePredicate) { const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? - setEmitFlags(createIdentifier((typePredicate).parameterName), EmitFlags.NoAsciiEscaping) : + setEmitFlags(createIdentifier(typePredicate.parameterName), EmitFlags.NoAsciiEscaping) : createThisTypeNode(); const typeNode = typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = createTypePredicateNode(parameterName, typeNode); @@ -3801,7 +3801,7 @@ namespace ts { if (isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible - const internalModuleReference = (declaration).moduleReference; + const internalModuleReference = declaration.moduleReference; const firstIdentifier = getFirstIdentifier(internalModuleReference); const importSymbol = resolveName(declaration, firstIdentifier.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, undefined, undefined, /*isUse*/ false); @@ -3926,7 +3926,7 @@ namespace ts { } function isComputedNonLiteralName(name: PropertyName): boolean { - return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral((name).expression); + return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral(name.expression); } function getRestType(source: Type, properties: PropertyName[], symbol: Symbol): Type { @@ -3984,7 +3984,7 @@ namespace ts { } const literalMembers: PropertyName[] = []; for (const element of pattern.elements) { - if (!(element as BindingElement).dotDotDotToken) { + if (!element.dotDotDotToken) { literalMembers.push(element.propertyName || element.name as Identifier); } } @@ -4080,7 +4080,7 @@ namespace ts { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForInStatement) { - const indexType = getIndexType(checkNonNullExpression((declaration.parent.parent).expression)); + const indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); return indexType.flags & (TypeFlags.TypeParameter | TypeFlags.Index) ? indexType : stringType; } @@ -4089,7 +4089,7 @@ namespace ts { // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, // or it may have led to an error inside getElementTypeOfIterable. - const forOfStatement = declaration.parent.parent; + const forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; } @@ -4142,7 +4142,7 @@ namespace ts { type = getContextualThisParameterType(func); } else { - type = getContextuallyTypedParameterType(declaration); + type = getContextuallyTypedParameterType(declaration); } if (type) { return addOptionality(type, isOptional); @@ -4163,7 +4163,7 @@ namespace ts { // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); } // No type specified and nothing can be inferred @@ -4224,7 +4224,7 @@ namespace ts { return checkDeclarationInitializer(element); } if (isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); @@ -4292,8 +4292,8 @@ namespace ts { // the parameter. function getTypeFromBindingPattern(pattern: BindingPattern, includePatternInType?: boolean, reportErrors?: boolean): Type { return pattern.kind === SyntaxKind.ObjectBindingPattern - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type @@ -5968,7 +5968,7 @@ namespace ts { function getCombinedMappedTypeOptionality(type: MappedType): number { const optionality = getMappedTypeOptionality(type); const modifiersType = getModifiersTypeFromMappedType(type); - return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); + return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0); } function isPartialMappedType(type: Type) { @@ -6509,9 +6509,8 @@ namespace ts { } if (node.initializer) { - const signatureDeclaration = node.parent; - const signature = getSignatureFromDeclaration(signatureDeclaration); - const parameterIndex = signatureDeclaration.parameters.indexOf(node); + const signature = getSignatureFromDeclaration(node.parent); + const parameterIndex = node.parent.parameters.indexOf(node); Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -6531,7 +6530,7 @@ namespace ts { if (parameterName.kind === SyntaxKind.Identifier) { return createIdentifierTypePredicate( parameterName && parameterName.escapedText as string, // TODO: GH#18217 - parameterName && getTypePredicateParameterIndex((node.parent as SignatureDeclaration).parameters, parameterName), + parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); } else { @@ -7179,11 +7178,11 @@ namespace ts { function getTypeReferenceName(node: TypeReferenceType): EntityNameOrEntityNameExpression | undefined { switch (node.kind) { case SyntaxKind.TypeReference: - return (node).typeName; + return node.typeName; case SyntaxKind.ExpressionWithTypeArguments: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. - const expr = (node).expression; + const expr = node.expression; if (isEntityNameExpression(expr)) { return expr; } @@ -7984,10 +7983,10 @@ namespace ts { } function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode, cacheSymbol: boolean) { - const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; + const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; const propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - getPropertyNameForKnownSymbolName(idText(((accessExpression.argumentExpression).name))) : + getPropertyNameForKnownSymbolName(idText((accessExpression.argumentExpression).name)) : undefined; if (propName !== undefined) { const prop = getPropertyOfType(objectType, propName); @@ -8031,7 +8030,7 @@ namespace ts { } } if (accessNode) { - const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? (accessNode).argumentExpression : (accessNode).indexType; + const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (indexType).value, typeToString(objectType)); } @@ -8121,10 +8120,9 @@ namespace ts { } function substituteIndexedMappedType(objectType: MappedType, type: IndexedAccessType) { - const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - const objectTypeMapper = (objectType).mapper; - const templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + const templateMapper = objectType.mapper ? combineTypeMappers(objectType.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode): Type { @@ -9233,13 +9231,12 @@ namespace ts { } if (source.kind === TypePredicateKind.Identifier) { - const sourcePredicate = source as IdentifierTypePredicate; const targetPredicate = target as IdentifierTypePredicate; - const sourceIndex = sourcePredicate.parameterIndex - (getThisParameter(sourceDeclaration) ? 1 : 0); + const sourceIndex = source.parameterIndex - (getThisParameter(sourceDeclaration) ? 1 : 0); const targetIndex = targetPredicate.parameterIndex - (getThisParameter(targetDeclaration) ? 1 : 0); if (sourceIndex !== targetIndex) { if (reportErrors) { - errorReporter(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourcePredicate.parameterName, targetPredicate.parameterName); + errorReporter(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return Ternary.False; @@ -10014,17 +10011,17 @@ namespace ts { } else if (isGenericMappedType(target)) { // A source type T is related to a target type { [P in X]: T[P] } - const template = getTemplateTypeFromMappedType(target); - const modifiers = getMappedTypeModifiers(target); + const template = getTemplateTypeFromMappedType(target); + const modifiers = getMappedTypeModifiers(target); if (!(modifiers & MappedTypeModifiers.ExcludeOptional)) { if (template.flags & TypeFlags.IndexedAccess && (template).objectType === source && - (template).indexType === getTypeParameterFromMappedType(target)) { + (template).indexType === getTypeParameterFromMappedType(target)) { return Ternary.True; } // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - const templateType = getTemplateTypeFromMappedType(target); + if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + const templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { errorInfo = saveErrorInfo; return result; @@ -10146,7 +10143,7 @@ namespace ts { result = Ternary.True; } else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : Ternary.False; + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : Ternary.False; } else { result = propertiesRelatedTo(source, target, reportStructuralErrors); @@ -10184,9 +10181,9 @@ namespace ts { getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { let result: Ternary; - if (result = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { - const mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + if (result = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + const mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return Ternary.False; @@ -10492,7 +10489,7 @@ namespace ts { if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U } // if T is related to U. - return kind === IndexKind.String && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); + return kind === IndexKind.String && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors); } if (isObjectTypeWithInferableIndex(source)) { let related = Ternary.True; @@ -11671,8 +11668,8 @@ namespace ts { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer // from S to T and from X to Y. - inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); - inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); } if (getObjectFlags(target) & ObjectFlags.Mapped) { const constraintType = getConstraintTypeFromMappedType(target); @@ -12235,7 +12232,7 @@ namespace ts { } function getAssignedTypeOfPropertyAssignment(node: PropertyAssignment | ShorthandPropertyAssignment): Type { - return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); } function getAssignedTypeOfShorthandPropertyAssignment(node: ShorthandPropertyAssignment): Type { @@ -12266,7 +12263,7 @@ namespace ts { } function getInitialTypeOfBindingElement(node: BindingElement): Type { - const pattern = node.parent; + const pattern = node.parent; const parentType = getInitialType(pattern.parent); const type = pattern.kind === SyntaxKind.ObjectBindingPattern ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : @@ -12292,21 +12289,21 @@ namespace ts { return stringType; } if (node.parent.parent.kind === SyntaxKind.ForOfStatement) { - return checkRightHandSideOfForOf((node.parent.parent).expression, (node.parent.parent).awaitModifier) || unknownType; + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; } return unknownType; } function getInitialType(node: VariableDeclaration | BindingElement) { return node.kind === SyntaxKind.VariableDeclaration ? - getInitialTypeOfVariableDeclaration(node) : - getInitialTypeOfBindingElement(node); + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node: VariableDeclaration | BindingElement | Expression) { return node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node); } function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) { @@ -12341,7 +12338,7 @@ namespace ts { function getTypeOfSwitchClause(clause: CaseClause | DefaultClause) { if (clause.kind === SyntaxKind.CaseClause) { - const caseType = getRegularTypeOfLiteralType(getTypeOfExpression((clause).expression)); + const caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); return isUnitType(caseType) ? caseType : undefined; } return neverType; @@ -12714,22 +12711,22 @@ namespace ts { if (declaredType === autoType || declaredType === autoArrayType) { const node = flow.node; const expr = node.kind === SyntaxKind.CallExpression ? - ((node).expression).expression : - ((node).left).expression; + (node.expression).expression : + (node.left).expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { const flowType = getTypeAtFlowNode(flow.antecedent); const type = getTypeFromFlowType(flowType); if (getObjectFlags(type) & ObjectFlags.EvolvingArray) { let evolvedType = type; if (node.kind === SyntaxKind.CallExpression) { - for (const arg of (node).arguments) { + for (const arg of node.arguments) { evolvedType = addEvolvingArrayElementType(evolvedType, arg); } } else { - const indexType = getTypeOfExpression(((node).left).argumentExpression); + const indexType = getTypeOfExpression((node.left).argumentExpression); if (isTypeAssignableToKind(indexType, TypeFlags.NumberLike)) { - evolvedType = addEvolvingArrayElementType(evolvedType, (node).right); + evolvedType = addEvolvingArrayElementType(evolvedType, node.right); } } return evolvedType === type ? flowType : createFlowType(evolvedType, isIncomplete(flowType)); @@ -13946,10 +13943,10 @@ namespace ts { } } - function getContainingObjectLiteral(func: FunctionLike) { + function getContainingObjectLiteral(func: FunctionLike): ObjectLiteralExpression | undefined { return (func.kind === SyntaxKind.MethodDeclaration || func.kind === SyntaxKind.GetAccessor || - func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : + func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent : undefined; } @@ -14089,17 +14086,17 @@ namespace ts { return getTypeFromTypeNode(typeNode); } if (declaration.kind === SyntaxKind.Parameter) { - const type = getContextuallyTypedParameterType(declaration); + const type = getContextuallyTypedParameterType(declaration); if (type) { return type; } } if (isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } if (isBindingPattern(declaration.parent)) { const parentDeclaration = declaration.parent.parent; - const name = (declaration as BindingElement).propertyName || (declaration as BindingElement).name; + const name = (declaration as BindingElement).propertyName || declaration.name; if (parentDeclaration.kind !== SyntaxKind.BindingElement) { const parentTypeNode = getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !isBindingPattern(name)) { @@ -14882,19 +14879,19 @@ namespace ts { let type: Type; if (memberDecl.kind === SyntaxKind.PropertyAssignment) { if (memberDecl.name.kind === SyntaxKind.ComputedPropertyName) { - const t = checkComputedPropertyName(memberDecl.name); + const t = checkComputedPropertyName(memberDecl.name); if (t.flags & TypeFlags.Literal) { literalName = escapeLeadingUnderscores("" + (t as LiteralType).value); } } - type = checkPropertyAssignment(memberDecl, checkMode); + type = checkPropertyAssignment(memberDecl, checkMode); } else if (memberDecl.kind === SyntaxKind.MethodDeclaration) { - type = checkObjectLiteralMethod(memberDecl, checkMode); + type = checkObjectLiteralMethod(memberDecl, checkMode); } else { Debug.assert(memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment); - type = checkExpressionForMutableLocation((memberDecl).name, checkMode); + type = checkExpressionForMutableLocation(memberDecl.name, checkMode); } if (jsdocType) { @@ -14913,8 +14910,8 @@ namespace ts { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. const isOptional = - (memberDecl.kind === SyntaxKind.PropertyAssignment && hasDefaultValue((memberDecl).initializer)) || - (memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment && (memberDecl).objectAssignmentInitializer); + (memberDecl.kind === SyntaxKind.PropertyAssignment && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= SymbolFlags.Optional; } @@ -14957,7 +14954,7 @@ namespace ts { hasComputedNumberProperty = false; typeFlags = 0; } - const type = checkExpression((memberDecl as SpreadAssignment).expression); + const type = checkExpression(memberDecl.expression); if (!isValidSpreadType(type)) { error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); return unknownType; @@ -15124,7 +15121,7 @@ namespace ts { if (isJsxAttribute(attributeDecl)) { const exprType = checkJsxAttribute(attributeDecl, checkMode); - const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); + const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; if (member.valueDeclaration) { @@ -15166,7 +15163,7 @@ namespace ts { const parent = openingLikeElement.parent.kind === SyntaxKind.JsxElement ? openingLikeElement.parent as JsxElement : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { - const childrenTypes: Type[] = checkJsxChildren(parent as JsxElement, checkMode); + const childrenTypes: Type[] = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { // Error if there is a attribute named "children" explicitly specified and children element. @@ -15230,7 +15227,7 @@ namespace ts { * @param node a JSXAttributes to be resolved of its type */ function checkJsxAttributes(node: JsxAttributes, checkMode: CheckMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent as JsxOpeningLikeElement, checkMode); + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } function getJsxType(name: __String) { @@ -15786,7 +15783,7 @@ namespace ts { if (!isJsxAttribute(attribute)) { continue; } - const attrName = attribute.name as Identifier; + const attrName = attribute.name; const isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, idText(attrName), typeToString(targetAttributesType)); @@ -15836,7 +15833,7 @@ namespace ts { function checkPropertyAccessibility(node: PropertyAccessExpression | QualifiedName | VariableLikeDeclaration, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean { const flags = getDeclarationModifierFlagsFromSymbol(prop); const errorNode = node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.VariableDeclaration ? - (node).name : + node.name : (node).right; if (getCheckFlags(prop) & CheckFlags.ContainsPrivate) { @@ -16447,7 +16444,7 @@ namespace ts { } if (node.kind === SyntaxKind.TaggedTemplateExpression) { - checkExpression((node).template); + checkExpression(node.template); } else if (node.kind !== SyntaxKind.Decorator) { forEach((node).arguments, argument => { @@ -16538,18 +16535,15 @@ namespace ts { } if (node.kind === SyntaxKind.TaggedTemplateExpression) { - const tagExpression = node; - // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === SyntaxKind.TemplateExpression) { + if (node.template.kind === SyntaxKind.TemplateExpression) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - const templateExpression = tagExpression.template; - const lastSpan = lastOrUndefined(templateExpression.templateSpans); + const lastSpan = lastOrUndefined(node.template.templateSpans); Debug.assert(lastSpan !== undefined); // we should always have at least one span. callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } @@ -16557,7 +16551,7 @@ namespace ts { // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. - const templateLiteral = tagExpression.template; + const templateLiteral = node.template; Debug.assert(templateLiteral.kind === SyntaxKind.NoSubstitutionTemplateLiteral); callIsIncomplete = !!templateLiteral.isUnterminated; } @@ -16567,10 +16561,9 @@ namespace ts { argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { - const callExpression = node; - if (!callExpression.arguments) { + if (!node.arguments) { // This only happens when we have something of the form: 'new C' - Debug.assert(callExpression.kind === SyntaxKind.NewExpression); + Debug.assert(node.kind === SyntaxKind.NewExpression); return signature.minArgumentCount === 0; } @@ -16578,9 +16571,9 @@ namespace ts { argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. - callIsIncomplete = callExpression.arguments.end === callExpression.end; + callIsIncomplete = node.arguments.end === node.end; - typeArguments = callExpression.typeArguments; + typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } @@ -16807,7 +16800,7 @@ namespace ts { excludeArgument: boolean[], reportErrors: boolean) { if (isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } const thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { @@ -16854,7 +16847,7 @@ namespace ts { */ function getThisArgumentOfCall(node: CallLikeExpression): LeftHandSideExpression { if (node.kind === SyntaxKind.CallExpression) { - const callee = (node).expression; + const callee = node.expression; if (callee.kind === SyntaxKind.PropertyAccessExpression) { return (callee as PropertyAccessExpression).expression; } @@ -16875,10 +16868,10 @@ namespace ts { */ function getEffectiveCallArguments(node: CallLikeExpression): ReadonlyArray { if (node.kind === SyntaxKind.TaggedTemplateExpression) { - const template = (node).template; + const template = node.template; const args: Expression[] = [undefined]; if (template.kind === SyntaxKind.TemplateExpression) { - forEach((template).templateSpans, span => { + forEach(template.templateSpans, span => { args.push(span.expression); }); } @@ -17130,7 +17123,7 @@ namespace ts { // a special first argument, and string literals get string literal types // unless we're reporting errors if (node.kind === SyntaxKind.Decorator) { - return getEffectiveDecoratorArgumentType(node, argIndex); + return getEffectiveDecoratorArgumentType(node, argIndex); } else if (argIndex === 0 && node.kind === SyntaxKind.TaggedTemplateExpression) { return getGlobalTemplateStringsArrayType(); @@ -17160,11 +17153,11 @@ namespace ts { function getEffectiveArgumentErrorNode(node: CallLikeExpression, argIndex: number, arg: Expression) { if (node.kind === SyntaxKind.Decorator) { // For a decorator, we use the expression of the decorator for error reporting. - return (node).expression; + return node.expression; } else if (argIndex === 0 && node.kind === SyntaxKind.TaggedTemplateExpression) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return (node).template; + return node.template; } else { return arg; @@ -17256,7 +17249,7 @@ namespace ts { // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. const signatureHelpTrailingComma = - candidatesOutArray && node.kind === SyntaxKind.CallExpression && (node).arguments.hasTrailingComma; + candidatesOutArray && node.kind === SyntaxKind.CallExpression && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument @@ -17810,17 +17803,17 @@ namespace ts { function resolveSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature { switch (node.kind) { case SyntaxKind.CallExpression: - return resolveCallExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray); case SyntaxKind.NewExpression: - return resolveNewExpression(node, candidatesOutArray); + return resolveNewExpression(node, candidatesOutArray); case SyntaxKind.TaggedTemplateExpression: - return resolveTaggedTemplateExpression(node, candidatesOutArray); + return resolveTaggedTemplateExpression(node, candidatesOutArray); case SyntaxKind.Decorator: - return resolveDecorator(node, candidatesOutArray); + return resolveDecorator(node, candidatesOutArray); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression((node).tagName), candidatesOutArray) || unknownSignature; + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; } Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -18206,7 +18199,7 @@ namespace ts { if (globalPromiseType !== emptyGenericType) { // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type promisedType = getAwaitedType(promisedType) || emptyObjectType; - return createTypeReference(globalPromiseType, [promisedType]); + return createTypeReference(globalPromiseType, [promisedType]); } return emptyObjectType; @@ -18237,7 +18230,7 @@ namespace ts { const functionFlags = getFunctionFlags(func); let type: Type; if (func.body.kind !== SyntaxKind.Block) { - type = checkExpressionCached(func.body, checkMode); + type = checkExpressionCached(func.body, checkMode); if (functionFlags & FunctionFlags.Async) { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the @@ -18522,9 +18515,9 @@ namespace ts { } if (produceDiagnostics && node.kind !== SyntaxKind.MethodDeclaration) { - checkCollisionWithCapturedSuperVariable(node, (node).name); - checkCollisionWithCapturedThisVariable(node, (node).name); - checkCollisionWithCapturedNewTargetVariable(node, (node).name); + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); } return type; @@ -18564,7 +18557,7 @@ namespace ts { // should not be checking assignability of a promise to the return type. Instead, we need to // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. - const exprType = checkExpression(node.body); + const exprType = checkExpression(node.body); if (returnOrPromisedType) { if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { // Async function const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -18845,9 +18838,9 @@ namespace ts { /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType: Type, property: ObjectLiteralElementLike, allProperties?: ReadonlyArray) { if (property.kind === SyntaxKind.PropertyAssignment || property.kind === SyntaxKind.ShorthandPropertyAssignment) { - const name = (property).name; + const name = property.name; if (name.kind === SyntaxKind.ComputedPropertyName) { - checkComputedPropertyName(name); + checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { return undefined; @@ -18861,11 +18854,11 @@ namespace ts { getIndexTypeOfType(objectLiteralType, IndexKind.String); if (type) { if (property.kind === SyntaxKind.ShorthandPropertyAssignment) { - return checkDestructuringAssignment(property, type); + return checkDestructuringAssignment(property, type); } else { // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment((property).initializer, type); + return checkDestructuringAssignment(property.initializer, type); } } else { @@ -18967,7 +18960,7 @@ namespace ts { target = (exprOrAssignment).name; } else { - target = exprOrAssignment; + target = exprOrAssignment; } if (target.kind === SyntaxKind.BinaryExpression && (target).operatorToken.kind === SyntaxKind.EqualsToken) { @@ -19369,7 +19362,7 @@ namespace ts { // It is worth asking whether this is what we really want though. // A place where we actually *are* concerned with the expressions' types are // in tagged templates. - forEach((node).templateSpans, templateSpan => { + forEach(node.templateSpans, templateSpan => { checkExpression(templateSpan.expression); }); @@ -19467,10 +19460,10 @@ namespace ts { // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. if (node.name.kind === SyntaxKind.ComputedPropertyName) { - checkComputedPropertyName(node.name); + checkComputedPropertyName(node.name); } - return checkExpressionForMutableLocation((node).initializer, checkMode); + return checkExpressionForMutableLocation(node.initializer, checkMode); } function checkObjectLiteralMethod(node: MethodDeclaration, checkMode?: CheckMode): Type { @@ -19481,7 +19474,7 @@ namespace ts { // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. if (node.name.kind === SyntaxKind.ComputedPropertyName) { - checkComputedPropertyName(node.name); + checkComputedPropertyName(node.name); } const uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -19555,8 +19548,8 @@ namespace ts { type = checkQualifiedName(node); } else { - const uninstantiatedType = checkExpressionWorker(node, checkMode); - type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + const uninstantiatedType = checkExpressionWorker(node, checkMode); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -20175,7 +20168,7 @@ namespace ts { // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { - const statements = (node.body).statements; + const statements = node.body.statements; let superCallStatement: ExpressionStatement; for (const statement of statements) { @@ -20216,7 +20209,7 @@ namespace ts { // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. if (node.name.kind === SyntaxKind.ComputedPropertyName) { - checkComputedPropertyName(node.name); + checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 @@ -21323,7 +21316,7 @@ namespace ts { if (node.name && node.name.kind === SyntaxKind.ComputedPropertyName) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals - checkComputedPropertyName(node.name); + checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(node)) { @@ -21925,7 +21918,7 @@ namespace ts { checkExternalEmitHelpers(node, ExternalEmitHelpers.Read); } - forEach((node.name).elements, checkSourceElement); + forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body if (node.initializer && getRootDeclaration(node).kind === SyntaxKind.Parameter && nodeIsMissing((getContainingFunction(node) as FunctionLikeDeclaration).body)) { @@ -21979,7 +21972,7 @@ namespace ts { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); if (node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement) { - checkVarDeclaredNamesNotShadowed(node); + checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); @@ -22029,7 +22022,7 @@ namespace ts { } function checkBindingElement(node: BindingElement) { - checkGrammarBindingElement(node); + checkGrammarBindingElement(node); return checkVariableLikeDeclaration(node); } @@ -22089,7 +22082,7 @@ namespace ts { forEach((node.initializer).declarations, checkVariableDeclaration); } else { - checkExpression(node.initializer); + checkExpression(node.initializer); } } @@ -22105,7 +22098,7 @@ namespace ts { checkGrammarForInOrForOfStatement(node); if (node.kind === SyntaxKind.ForOfStatement) { - if ((node).awaitModifier) { + if (node.awaitModifier) { const functionFlags = getFunctionFlags(getContainingFunction(node)); if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Async)) === FunctionFlags.Async && languageVersion < ScriptTarget.ESNext) { // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper @@ -22127,7 +22120,7 @@ namespace ts { checkForInOrForOfVariableDeclaration(node); } else { - const varExpr = node.initializer; + const varExpr = node.initializer; const iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side @@ -22179,7 +22172,7 @@ namespace ts { // for (Var in Expr) Statement // Var must be an expression classified as a reference of type Any or the String primitive type, // and Expr must be an expression of type Any, an object type, or a type parameter type. - const varExpr = node.initializer; + const varExpr = node.initializer; const leftType = checkExpression(varExpr); if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -22646,11 +22639,10 @@ namespace ts { } if (produceDiagnostics && clause.kind === SyntaxKind.CaseClause) { - const caseClause = clause; // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. - let caseType = checkExpression(caseClause.expression); + let caseType = checkExpression(clause.expression); const caseIsLiteral = isLiteralType(caseType); let comparedExpressionType = expressionType; if (!caseIsLiteral || !expressionIsLiteral) { @@ -22659,7 +22651,7 @@ namespace ts { } if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { // expressionType is not comparable to caseType, try the reversed check and report errors if it fails - checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); + checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined); } } forEach(clause.statements, checkSourceElement); @@ -22753,7 +22745,7 @@ namespace ts { }); if (getObjectFlags(type) & ObjectFlags.Class && isClassLike(type.symbol.valueDeclaration)) { - const classDeclaration = type.symbol.valueDeclaration; + const classDeclaration = type.symbol.valueDeclaration; for (const member of classDeclaration.members) { // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, @@ -22844,7 +22836,7 @@ namespace ts { case "symbol": case "void": case "object": - error(name, message, (name).escapedText as string); + error(name, message, name.escapedText as string); } } @@ -23349,11 +23341,11 @@ namespace ts { } function computeMemberValue(member: EnumMember, autoValue: number) { - if (isComputedNonLiteralName(member.name)) { + if (isComputedNonLiteralName(member.name)) { error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { - const text = getTextOfPropertyName(member.name); + const text = getTextOfPropertyName(member.name); if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); } @@ -23739,17 +23731,17 @@ namespace ts { function getFirstIdentifier(node: EntityNameOrEntityNameExpression): Identifier { switch (node.kind) { case SyntaxKind.Identifier: - return node; + return node; case SyntaxKind.QualifiedName: do { - node = (node).left; + node = node.left; } while (node.kind !== SyntaxKind.Identifier); - return node; + return node; case SyntaxKind.PropertyAccessExpression: do { - node = (node).expression; + node = node.expression; } while (node.kind !== SyntaxKind.Identifier); - return node; + return node; } } @@ -23759,7 +23751,7 @@ namespace ts { error(moduleName, Diagnostics.String_literal_expected); return false; } - const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent); + const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent); if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { error(moduleName, node.kind === SyntaxKind.ExportDeclaration ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : @@ -23835,10 +23827,10 @@ namespace ts { } if (importClause.namedBindings) { if (importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { - checkImportBinding(importClause.namedBindings); + checkImportBinding(importClause.namedBindings); } else { - forEach((importClause.namedBindings).elements, checkImportBinding); + forEach(importClause.namedBindings.elements, checkImportBinding); } } } @@ -23862,7 +23854,7 @@ namespace ts { if (target !== unknownSymbol) { if (target.flags & SymbolFlags.Value) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - const moduleName = getFirstIdentifier(node.moduleReference); + const moduleName = getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, SymbolFlags.Value | SymbolFlags.Namespace).flags & SymbolFlags.Namespace)) { error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName)); } @@ -23931,7 +23923,7 @@ namespace ts { if (compilerOptions.declaration) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } - if (!(node.parent.parent).moduleSpecifier) { + if (!node.parent.parent.moduleSpecifier) { const exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, @@ -23951,7 +23943,7 @@ namespace ts { return; } - const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; + const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) { if (node.isExportEquals) { error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); @@ -24639,11 +24631,11 @@ namespace ts { /*all meanings*/ SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); } - if (entityName.kind !== SyntaxKind.PropertyAccessExpression && isInRightSideOfImportOrExportAssignment(entityName)) { + if (entityName.kind !== SyntaxKind.PropertyAccessExpression && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - const importEqualsDeclaration = getAncestor(entityName, SyntaxKind.ImportEqualsDeclaration); + const importEqualsDeclaration = getAncestor(entityName, SyntaxKind.ImportEqualsDeclaration); Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } if (isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { @@ -24837,8 +24829,8 @@ namespace ts { /** Returns the target of an export specifier without following aliases */ function getExportSpecifierLocalTargetSymbol(node: ExportSpecifier): Symbol { - return (node.parent.parent).moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node) : + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : resolveEntityName(node.propertyName || node.name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); } @@ -25299,7 +25291,7 @@ namespace ts { } function getEnumMemberValue(node: EnumMember): string | number { - computeEnumMemberValues(node.parent); + computeEnumMemberValues(node.parent); return getNodeLinks(node).enumMemberValue; } @@ -25315,7 +25307,7 @@ namespace ts { function getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number { if (node.kind === SyntaxKind.EnumMember) { - return getEnumMemberValue(node); + return getEnumMemberValue(node); } const symbol = getNodeLinks(node).resolvedSymbol; @@ -25630,7 +25622,7 @@ namespace ts { if (!moduleSymbol) { return undefined; } - return getDeclarationOfKind(moduleSymbol, SyntaxKind.SourceFile) as SourceFile; + return getDeclarationOfKind(moduleSymbol, SyntaxKind.SourceFile); } function initializeTypeChecker() { @@ -26352,13 +26344,13 @@ namespace ts { const name = prop.name; if (name.kind === SyntaxKind.ComputedPropertyName) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name); + checkGrammarComputedPropertyName(name); } - if (prop.kind === SyntaxKind.ShorthandPropertyAssignment && !inDestructuring && (prop).objectAssignmentInitializer) { + if (prop.kind === SyntaxKind.ShorthandPropertyAssignment && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return grammarErrorOnNode((prop).equalsToken, Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + return grammarErrorOnNode(prop.equalsToken, Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } // Modifiers are never allowed on properties except for 'async' on a method declaration @@ -26383,9 +26375,9 @@ namespace ts { case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark((prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); + checkGrammarForInvalidQuestionMark(prop.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === SyntaxKind.NumericLiteral) { - checkGrammarNumericLiteral(name); + checkGrammarNumericLiteral(name); } // falls through case SyntaxKind.MethodDeclaration: @@ -26437,8 +26429,7 @@ namespace ts { continue; } - const jsxAttr = (attr); - const name = jsxAttr.name; + const { name, initializer } = attr; if (!seen.get(name.escapedText)) { seen.set(name.escapedText, true); } @@ -26446,9 +26437,8 @@ namespace ts { return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - const initializer = jsxAttr.initializer; - if (initializer && initializer.kind === SyntaxKind.JsxExpression && !(initializer).expression) { - return grammarErrorOnNode(jsxAttr.initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + if (initializer && initializer.kind === SyntaxKind.JsxExpression && !initializer.expression) { + return grammarErrorOnNode(initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } } @@ -26708,7 +26698,7 @@ namespace ts { function checkGrammarBindingElement(node: BindingElement) { if (node.dotDotDotToken) { - const elements = (node.parent).elements; + const elements = node.parent.elements; if (node !== last(elements)) { return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -26793,7 +26783,7 @@ namespace ts { } } else { - const elements = (name).elements; + const elements = name.elements; for (const element of elements) { if (!isOmittedExpression(element)) { return checkESModuleMarker(element.name); @@ -26804,12 +26794,12 @@ namespace ts { function checkGrammarNameInLetOrConstDeclarations(name: Identifier | BindingPattern): boolean { if (name.kind === SyntaxKind.Identifier) { - if ((name).originalKeywordKind === SyntaxKind.LetKeyword) { + if (name.originalKeywordKind === SyntaxKind.LetKeyword) { return grammarErrorOnNode(name, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } else { - const elements = (name).elements; + const elements = name.elements; for (const element of elements) { if (!isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index f18a32889aa87..a9b3568bfe67c 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -350,8 +350,8 @@ namespace ts { // and also for non-optional initialized parameters that aren't a parameter property // these types may need to add `undefined`. const shouldUseResolverType = declaration.kind === SyntaxKind.Parameter && - (resolver.isRequiredInitializedParameter(declaration as ParameterDeclaration) || - resolver.isOptionalUninitializedParameterProperty(declaration as ParameterDeclaration)); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { // Write the type emitType(type); @@ -839,10 +839,10 @@ namespace ts { function isVisibleNamedBinding(namedBindings: NamespaceImport | NamedImports): boolean { if (namedBindings) { if (namedBindings.kind === SyntaxKind.NamespaceImport) { - return resolver.isDeclarationVisible(namedBindings); + return resolver.isDeclarationVisible(namedBindings); } else { - return forEach((namedBindings).elements, namedImport => resolver.isDeclarationVisible(namedImport)); + return namedBindings.elements.some(namedImport => resolver.isDeclarationVisible(namedImport)); } } } @@ -865,11 +865,11 @@ namespace ts { } if (node.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { write("* as "); - writeTextOfNode(currentText, (node.importClause.namedBindings).name); + writeTextOfNode(currentText, node.importClause.namedBindings.name); } else { write("{ "); - emitCommaList((node.importClause.namedBindings).elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); + emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); write(" }"); } } @@ -886,18 +886,8 @@ namespace ts { // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' // so compiler will treat them as external modules. resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== SyntaxKind.ModuleDeclaration; - let moduleSpecifier: Node; - if (parent.kind === SyntaxKind.ImportEqualsDeclaration) { - const node = parent as ImportEqualsDeclaration; - moduleSpecifier = getExternalModuleImportEqualsDeclarationExpression(node); - } - else if (parent.kind === SyntaxKind.ModuleDeclaration) { - moduleSpecifier = (parent).name; - } - else { - const node = parent as (ImportDeclaration | ExportDeclaration); - moduleSpecifier = node.moduleSpecifier; - } + const moduleSpecifier = parent.kind === SyntaxKind.ImportEqualsDeclaration ? getExternalModuleImportEqualsDeclarationExpression(parent) : + parent.kind === SyntaxKind.ModuleDeclaration ? parent.name : parent.moduleSpecifier; if (moduleSpecifier.kind === SyntaxKind.StringLiteral && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { const moduleName = getExternalModuleNameFromDeclaration(host, resolver, parent); @@ -1293,7 +1283,7 @@ namespace ts { // so there is no check needed to see if declaration is visible if (node.kind !== SyntaxKind.VariableDeclaration || isVariableDeclarationVisible(node)) { if (isBindingPattern(node.name)) { - emitBindingPattern(node.name); + emitBindingPattern(node.name); } else { writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); @@ -1301,7 +1291,7 @@ namespace ts { // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor // we don't want to emit property declaration with "?" if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || - (node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(node))) && hasQuestionToken(node)) { + (node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(node))) && hasQuestionToken(node)) { write("?"); } if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) { @@ -1389,7 +1379,7 @@ namespace ts { if (bindingElement.name) { if (isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); + emitBindingPattern(bindingElement.name); } else { writeTextOfNode(currentText, bindingElement.name); @@ -1782,7 +1772,7 @@ namespace ts { // For bindingPattern, we can't simply writeTextOfNode from the source file // because we want to omit the initializer and using writeTextOfNode will result in initializer get emitted. // Therefore, we will have to recursively emit each element in the bindingPattern. - emitBindingPattern(node.name); + emitBindingPattern(node.name); } else { writeTextOfNode(currentText, node.name); @@ -1921,7 +1911,7 @@ namespace ts { // emit : declare function foo([a, [[b]], c]: [number, [[string]], number]): void; // original with rest: function foo([a, ...c]) {} // emit : declare function foo([a, ...c]): void; - emitBindingPattern(bindingElement.name); + emitBindingPattern(bindingElement.name); } else { Debug.assert(bindingElement.name.kind === SyntaxKind.Identifier); diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 735e0d67f472e..df1394efd006e 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -951,7 +951,7 @@ namespace ts { function emitEntityName(node: EntityName) { if (node.kind === SyntaxKind.Identifier) { - emitExpression(node); + emitExpression(node); } else { emit(node); @@ -1709,7 +1709,7 @@ namespace ts { emit(node); } else { - emitExpression(node); + emitExpression(node); } } } @@ -2068,7 +2068,7 @@ namespace ts { function emitModuleReference(node: ModuleReference) { if (node.kind === SyntaxKind.Identifier) { - emitExpression(node); + emitExpression(node); } else { emit(node); @@ -2472,12 +2472,12 @@ namespace ts { function emitPrologueDirectivesIfNeeded(sourceFileOrBundle: Bundle | SourceFile) { if (isSourceFile(sourceFileOrBundle)) { - setSourceFile(sourceFileOrBundle as SourceFile); - emitPrologueDirectives((sourceFileOrBundle as SourceFile).statements); + setSourceFile(sourceFileOrBundle); + emitPrologueDirectives(sourceFileOrBundle.statements); } else { const seenPrologueDirectives = createMap(); - for (const sourceFile of (sourceFileOrBundle as Bundle).sourceFiles) { + for (const sourceFile of sourceFileOrBundle.sourceFiles) { setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 8166196e469b1..647ae6983fab1 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -644,7 +644,7 @@ namespace ts { } export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); + return updateSignatureDeclaration(node, typeParameters, parameters, type); } export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) { @@ -652,7 +652,7 @@ namespace ts { } export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) { - return updateSignatureDeclaration(node, typeParameters, parameters, type); + return updateSignatureDeclaration(node, typeParameters, parameters, type); } export function createTypeQueryNode(exprName: EntityName) { @@ -1285,7 +1285,7 @@ namespace ts { export function createYield(asteriskTokenOrExpression?: AsteriskToken | Expression, expression?: Expression) { const node = createSynthesizedNode(SyntaxKind.YieldExpression); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === SyntaxKind.AsteriskToken ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== SyntaxKind.AsteriskToken ? asteriskTokenOrExpression : expression; + node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== SyntaxKind.AsteriskToken ? asteriskTokenOrExpression : expression; return node; } @@ -3415,13 +3415,13 @@ namespace ts { switch (property.kind) { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); + return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); case SyntaxKind.PropertyAssignment: - return createExpressionForPropertyAssignment(property, receiver); + return createExpressionForPropertyAssignment(property, receiver); case SyntaxKind.ShorthandPropertyAssignment: - return createExpressionForShorthandPropertyAssignment(property, receiver); + return createExpressionForShorthandPropertyAssignment(property, receiver); case SyntaxKind.MethodDeclaration: - return createExpressionForMethodDeclaration(property, receiver); + return createExpressionForMethodDeclaration(property, receiver); } } @@ -4065,13 +4065,13 @@ namespace ts { export function parenthesizePostfixOperand(operand: Expression) { return isLeftHandSideExpression(operand) - ? operand + ? operand : setTextRange(createParen(operand), operand); } export function parenthesizePrefixOperand(operand: Expression) { return isUnaryExpression(operand) - ? operand + ? operand : setTextRange(createParen(operand), operand); } @@ -4203,7 +4203,7 @@ namespace ts { export function parenthesizeConciseBody(body: ConciseBody): ConciseBody { if (!isBlock(body) && getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === SyntaxKind.ObjectLiteralExpression) { - return setTextRange(createParen(body), body); + return setTextRange(createParen(body), body); } return body; @@ -4370,10 +4370,10 @@ namespace ts { const name = namespaceDeclaration.name; return isGeneratedIdentifier(name) ? name : createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name)); } - if (node.kind === SyntaxKind.ImportDeclaration && (node).importClause) { + if (node.kind === SyntaxKind.ImportDeclaration && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === SyntaxKind.ExportDeclaration && (node).moduleSpecifier) { + if (node.kind === SyntaxKind.ExportDeclaration && node.moduleSpecifier) { return getGeneratedNameForNode(node); } return undefined; @@ -4494,7 +4494,7 @@ namespace ts { // `{a}` in `let [{a} = 1] = ...` // `[a]` in `let [[a]] = ...` // `[a]` in `let [[a] = 1] = ...` - return bindingElement.name; + return bindingElement.name; } if (isObjectLiteralElementLike(bindingElement)) { @@ -4556,12 +4556,12 @@ namespace ts { case SyntaxKind.Parameter: case SyntaxKind.BindingElement: // `...` in `let [...a] = ...` - return (bindingElement).dotDotDotToken; + return bindingElement.dotDotDotToken; case SyntaxKind.SpreadElement: case SyntaxKind.SpreadAssignment: // `...` in `[...a] = ...` - return bindingElement; + return bindingElement; } return undefined; @@ -4577,8 +4577,8 @@ namespace ts { // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` // `1` in `let { 1: b } = ...` - if ((bindingElement).propertyName) { - const propertyName = (bindingElement).propertyName; + if (bindingElement.propertyName) { + const propertyName = bindingElement.propertyName; return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; @@ -4591,8 +4591,8 @@ namespace ts { // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` // `1` in `({ 1: b } = ...)` - if ((bindingElement).name) { - const propertyName = (bindingElement).name; + if (bindingElement.name) { + const propertyName = bindingElement.name; return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; @@ -4602,7 +4602,7 @@ namespace ts { case SyntaxKind.SpreadAssignment: // `a` in `({ ...a } = ...)` - return (bindingElement).name; + return bindingElement.name; } const target = getTargetOfBindingOrAssignmentElement(bindingElement); @@ -4639,7 +4639,7 @@ namespace ts { Debug.assertNode(element.name, isIdentifier); return setOriginalNode(setTextRange(createSpread(element.name), element), element); } - const expression = convertToAssignmentElementTarget(element.name); + const expression = convertToAssignmentElementTarget(element.name); return element.initializer ? setOriginalNode( setTextRange( @@ -4661,7 +4661,7 @@ namespace ts { return setOriginalNode(setTextRange(createSpreadAssignment(element.name), element), element); } if (element.propertyName) { - const expression = convertToAssignmentElementTarget(element.name); + const expression = convertToAssignmentElementTarget(element.name); return setOriginalNode(setTextRange(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression), element), element); } Debug.assertNode(element.name, isIdentifier); @@ -4694,7 +4694,7 @@ namespace ts { ); } Debug.assertNode(node, isObjectLiteralExpression); - return node; + return node; } export function convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern) { @@ -4708,7 +4708,7 @@ namespace ts { ); } Debug.assertNode(node, isArrayLiteralExpression); - return node; + return node; } export function convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression { @@ -4717,6 +4717,6 @@ namespace ts { } Debug.assertNode(node, isExpression); - return node; + return node; } } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index b71983b978379..8426c8de2afe8 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -690,7 +690,7 @@ namespace ts { // Prime the scanner. nextToken(); if (token() === SyntaxKind.EndOfFileToken) { - sourceFile.endOfFileToken = parseTokenNode(); + sourceFile.endOfFileToken = parseTokenNode(); } else if (token() === SyntaxKind.OpenBraceToken || lookAhead(() => token() === SyntaxKind.StringLiteral)) { @@ -773,7 +773,7 @@ namespace ts { sourceFile.statements = parseList(ParsingContext.SourceElements, parseStatement); Debug.assert(token() === SyntaxKind.EndOfFileToken); - sourceFile.endOfFileToken = addJSDocComment(parseTokenNode() as EndOfFileToken); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); @@ -1794,7 +1794,7 @@ namespace ts { // into an actual .ConstructorDeclaration. const methodDeclaration = node; const nameIsConstructor = methodDeclaration.name.kind === SyntaxKind.Identifier && - (methodDeclaration.name).originalKeywordKind === SyntaxKind.ConstructorKeyword; + methodDeclaration.name.originalKeywordKind === SyntaxKind.ConstructorKeyword; return !nameIsConstructor; } @@ -3175,7 +3175,7 @@ namespace ts { // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } // It wasn't an assignment or a lambda. This is a conditional expression: @@ -3624,7 +3624,7 @@ namespace ts { } } else { - leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); } } @@ -4079,7 +4079,7 @@ namespace ts { else { Debug.assert(opening.kind === SyntaxKind.JsxSelfClosingElement); // Nothing else to do for self-closing elements - result = opening; + result = opening; } // If the user writes the invalid code '
' in an expression context (i.e. not wrapped in @@ -4097,7 +4097,7 @@ namespace ts { badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -5253,7 +5253,7 @@ namespace ts { if (node.decorators || node.modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - const missing = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const missing = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 1f2a3bfcd5de0..2cba011131edd 100755 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -812,7 +812,7 @@ namespace ts { if (!result) { // There were no unresolved/ambient resolutions. Debug.assert(resolutions.length === moduleNames.length); - return resolutions; + return resolutions; } let j = 0; diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 0956c1075efb8..7e4769a3e50a7 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -1995,7 +1995,7 @@ namespace ts { // If we are here it is because this is a destructuring assignment. if (isDestructuringAssignment(node)) { return flattenDestructuringAssignment( - node, + node, visitor, context, FlattenLevel.All, @@ -2023,7 +2023,7 @@ namespace ts { ); } else { - assignment = createBinary(decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression)); + assignment = createBinary(decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression)); setTextRange(assignment, decl); } @@ -2632,10 +2632,10 @@ namespace ts { function visit(node: Identifier | BindingPattern) { if (node.kind === SyntaxKind.Identifier) { - state.hoistedLocalVariables.push((node)); + state.hoistedLocalVariables.push(node); } else { - for (const element of (node).elements) { + for (const element of node.elements) { if (!isOmittedExpression(element)) { visit(element.name); } @@ -2716,7 +2716,7 @@ namespace ts { convertedLoopState = outerConvertedLoopState; if (loopOutParameters.length || lexicalEnvironment) { - const statements = isBlock(loopBody) ? (loopBody).statements.slice() : [loopBody]; + const statements = isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, CopyDirection.ToOutParameter, statements); } @@ -2856,7 +2856,7 @@ namespace ts { loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); } else { - let clone = getMutableClone(node); + let clone = getMutableClone(node); // clean statement part clone.statement = undefined; // visit childnodes to transform initializer/condition/incrementor parts @@ -3039,7 +3039,7 @@ namespace ts { switch (property.kind) { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - const accessors = getAllAccessorDeclarations(node.properties, property); + const accessors = getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); } @@ -3047,15 +3047,15 @@ namespace ts { break; case SyntaxKind.MethodDeclaration: - expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; case SyntaxKind.PropertyAssignment: - expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; case SyntaxKind.ShorthandPropertyAssignment: - expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 905686c8861e5..0c6b25cf0b524 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -183,7 +183,7 @@ namespace ts { : visitNode(node.initializer, visitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), - visitNode((node).statement, asyncBodyVisitor, isStatement, liftToBlock) + visitNode(node.statement, asyncBodyVisitor, isStatement, liftToBlock) ); } diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 82ff52ead90ee..74afe44a0972a 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -167,7 +167,7 @@ namespace ts { objects.push(createObjectLiteral(chunkObject)); chunkObject = undefined; } - const target = (e as SpreadAssignment).expression; + const target = e.expression; objects.push(visitNode(target, visitor, isExpression)); } else { @@ -175,8 +175,7 @@ namespace ts { chunkObject = []; } if (e.kind === SyntaxKind.PropertyAssignment) { - const p = e as PropertyAssignment; - chunkObject.push(createPropertyAssignment(p.name, visitNode(p.initializer, visitor, isExpression))); + chunkObject.push(createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression))); } else { chunkObject.push(visitNode(e, visitor, isObjectLiteralElementLike)); diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 8df05e4f3abbf..1a4c82020c77c 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -1771,16 +1771,15 @@ namespace ts { for (let i = clausesWritten; i < numClauses; i++) { const clause = caseBlock.clauses[i]; if (clause.kind === SyntaxKind.CaseClause) { - const caseClause = clause; - if (containsYield(caseClause.expression) && pendingClauses.length > 0) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } pendingClauses.push( createCaseClause( - visitNode(caseClause.expression, visitor, isExpression), + visitNode(clause.expression, visitor, isExpression), [ - createInlineBreak(clauseLabels[i], /*location*/ caseClause.expression) + createInlineBreak(clauseLabels[i], /*location*/ clause.expression) ] ) ); diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index 35eaae2a5cff5..94e41af9c2890 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -57,19 +57,19 @@ namespace ts { function transformJsxChildToExpression(node: JsxChild): Expression { switch (node.kind) { case SyntaxKind.JsxText: - return visitJsxText(node); + return visitJsxText(node); case SyntaxKind.JsxExpression: - return visitJsxExpression(node); + return visitJsxExpression(node); case SyntaxKind.JsxElement: - return visitJsxElement(node, /*isChild*/ true); + return visitJsxElement(node, /*isChild*/ true); case SyntaxKind.JsxSelfClosingElement: - return visitJsxSelfClosingElement(node, /*isChild*/ true); + return visitJsxSelfClosingElement(node, /*isChild*/ true); case SyntaxKind.JsxFragment: - return visitJsxFragment(node, /*isChild*/ true); + return visitJsxFragment(node, /*isChild*/ true); default: Debug.failBadSyntaxKind(node); @@ -171,15 +171,15 @@ namespace ts { else if (node.kind === SyntaxKind.StringLiteral) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string - const literal = createLiteral(tryDecodeEntities((node).text) || (node).text); - literal.singleQuote = (node as StringLiteral).singleQuote !== undefined ? (node as StringLiteral).singleQuote : !isStringDoubleQuoted(node as StringLiteral, currentSourceFile); + const literal = createLiteral(tryDecodeEntities(node.text) || node.text); + literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !isStringDoubleQuoted(node, currentSourceFile); return setTextRange(literal, node); } else if (node.kind === SyntaxKind.JsxExpression) { if (node.expression === undefined) { return createTrue(); } - return visitJsxExpression(node); + return visitJsxExpression(node); } else { Debug.failBadSyntaxKind(node); @@ -279,10 +279,10 @@ namespace ts { function getTagName(node: JsxElement | JsxOpeningLikeElement): Expression { if (node.kind === SyntaxKind.JsxElement) { - return getTagName((node).openingElement); + return getTagName(node.openingElement); } else { - const name = (node).tagName; + const name = node.tagName; if (isIdentifier(name) && isIntrinsicJsxName(name.escapedText)) { return createLiteral(idText(name)); } diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 2c75964d61660..b55dc583aa93e 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -533,7 +533,7 @@ namespace ts { } if (isImportCall(node)) { - return visitImportCallExpression(node); + return visitImportCallExpression(node); } else { return visitEachChild(node, importCallExpressionVisitor, context); diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index 2e6f6d84b51b3..d4bae7230521d 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -343,13 +343,12 @@ namespace ts { continue; } - const exportDecl = externalImport; - if (!exportDecl.exportClause) { + if (!externalImport.exportClause) { // export * from ... continue; } - for (const element of exportDecl.exportClause.elements) { + for (const element of externalImport.exportClause.elements) { // write name of indirectly exported entry, i.e. 'export {x} from ...' exportedNames.push( createPropertyAssignment( @@ -472,7 +471,7 @@ namespace ts { const importVariableName = getLocalNameForExternalImport(entry, currentSourceFile); switch (entry.kind) { case SyntaxKind.ImportDeclaration: - if (!(entry).importClause) { + if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; @@ -491,7 +490,7 @@ namespace ts { case SyntaxKind.ExportDeclaration: Debug.assert(importVariableName !== undefined); - if ((entry).exportClause) { + if (entry.exportClause) { // export {a, b as c} from 'foo' // // emit as: @@ -501,7 +500,7 @@ namespace ts { // "c": _["b"] // }); const properties: PropertyAssignment[] = []; - for (const e of (entry).exportClause.elements) { + for (const e of entry.exportClause.elements) { properties.push( createPropertyAssignment( createLiteral(idText(e.name)), diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 0e70b3099c005..059ae73ea2bfa 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -242,13 +242,13 @@ namespace ts { } switch (node.kind) { case SyntaxKind.ImportDeclaration: - return visitImportDeclaration(node); + return visitImportDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: - return visitImportEqualsDeclaration(node); + return visitImportEqualsDeclaration(node); case SyntaxKind.ExportAssignment: - return visitExportAssignment(node); + return visitExportAssignment(node); case SyntaxKind.ExportDeclaration: - return visitExportDeclaration(node); + return visitExportDeclaration(node); default: Debug.fail("Unhandled ellided statement"); } @@ -2010,7 +2010,7 @@ namespace ts { case SyntaxKind.Identifier: // Create a clone of the name with a new parent, and treat it as if it were // a source tree node for the purposes of the checker. - const name = getMutableClone(node); + const name = getMutableClone(node); name.flags &= ~NodeFlags.Synthesized; name.original = undefined; name.parent = getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. @@ -2027,7 +2027,7 @@ namespace ts { return name; case SyntaxKind.QualifiedName: - return serializeQualifiedNameAsExpression(node, useFallback); + return serializeQualifiedNameAsExpression(node, useFallback); } } @@ -2091,9 +2091,9 @@ namespace ts { function getExpressionForPropertyName(member: ClassElement | EnumMember, generateNameForComputedPropertyName: boolean): Expression { const name = member.name; if (isComputedPropertyName(name)) { - return generateNameForComputedPropertyName && !isSimpleInlineableExpression((name).expression) + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? getGeneratedNameForNode(name) - : (name).expression; + : name.expression; } else if (isIdentifier(name)) { return createLiteral(idText(name)); @@ -2961,7 +2961,7 @@ namespace ts { const body = node.body; if (body.kind === SyntaxKind.ModuleBlock) { saveStateAndInvoke(body, body => addRange(statements, visitNodes((body).statements, namespaceElementVisitor, isStatement))); - statementsLocation = (body).statements; + statementsLocation = body.statements; blockLocation = body; } else { @@ -3547,9 +3547,7 @@ namespace ts { return undefined; } - return isPropertyAccessExpression(node) || isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; + return isPropertyAccessExpression(node) || isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined; } } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 4e5b5700d297d..63214d68e5d12 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -904,11 +904,10 @@ namespace ts { return; default: if (isFunctionLike(node)) { - const name = (node).name; - if (name && name.kind === SyntaxKind.ComputedPropertyName) { + if (node.name && node.name.kind === SyntaxKind.ComputedPropertyName) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. - traverse((name).expression); + traverse(node.name.expression); return; } } @@ -1219,15 +1218,15 @@ namespace ts { } export function getInvokedExpression(node: CallLikeExpression): Expression { - if (node.kind === SyntaxKind.TaggedTemplateExpression) { - return (node).tag; - } - else if (isJsxOpeningLikeElement(node)) { - return node.tagName; + switch (node.kind) { + case SyntaxKind.TaggedTemplateExpression: + return node.tag; + case SyntaxKind.JsxOpeningElement: + case SyntaxKind.JsxSelfClosingElement: + return node.tagName; + default: + return node.expression; } - - // Will either be a CallExpression, NewExpression, or Decorator. - return (node).expression; } export function nodeCanBeDecorated(node: ClassDeclaration): true; @@ -1559,7 +1558,7 @@ namespace ts { if (node.kind === SyntaxKind.ImportEqualsDeclaration) { const reference = (node).moduleReference; if (reference.kind === SyntaxKind.ExternalModuleReference) { - return (reference).expression; + return reference.expression; } } if (node.kind === SyntaxKind.ExportDeclaration) { @@ -1571,20 +1570,20 @@ namespace ts { } export function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): ImportEqualsDeclaration | NamespaceImport { - if (node.kind === SyntaxKind.ImportEqualsDeclaration) { - return node; - } - - const importClause = (node).importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { - return importClause.namedBindings; + switch (node.kind) { + case SyntaxKind.ImportDeclaration: + return node.importClause && tryCast(node.importClause.namedBindings, isNamespaceImport); + case SyntaxKind.ImportEqualsDeclaration: + return node; + case SyntaxKind.ExportDeclaration: + return undefined; + default: + return Debug.assertNever(node); } } export function isDefaultImport(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) { - return node.kind === SyntaxKind.ImportDeclaration - && (node).importClause - && !!(node).importClause.name; + return node.kind === SyntaxKind.ImportDeclaration && node.importClause && !!node.importClause.name; } export function hasQuestionToken(node: Node) { @@ -2127,8 +2126,8 @@ namespace ts { export function isDynamicName(name: DeclarationName): boolean { return name.kind === SyntaxKind.ComputedPropertyName && - !isStringOrNumericLiteral((name).expression) && - !isWellKnownSymbolSyntactically((name).expression); + !isStringOrNumericLiteral(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); } /** @@ -2168,7 +2167,7 @@ namespace ts { if (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) { - return (node as LiteralLikeNode).text; + return node.text; } } @@ -2183,7 +2182,7 @@ namespace ts { if (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) { - return escapeLeadingUnderscores((node as LiteralLikeNode).text); + return escapeLeadingUnderscores(node.text); } } @@ -4258,13 +4257,12 @@ namespace ts { // Covers remaining cases switch (hostNode.kind) { case SyntaxKind.VariableStatement: - if ((hostNode as VariableStatement).declarationList && - (hostNode as VariableStatement).declarationList.declarations[0]) { - return getDeclarationIdentifier((hostNode as VariableStatement).declarationList.declarations[0]); + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; case SyntaxKind.ExpressionStatement: - const expr = (hostNode as ExpressionStatement).expression; + const expr = hostNode.expression; switch (expr.kind) { case SyntaxKind.PropertyAccessExpression: return (expr as PropertyAccessExpression).name; @@ -4297,7 +4295,7 @@ namespace ts { } export function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined { - return declaration.name || nameForNamelessJSDocTypedef(declaration as JSDocTypedefTag); + return declaration.name || nameForNamelessJSDocTypedef(declaration); } export function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined { @@ -4353,7 +4351,7 @@ namespace ts { export function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray | undefined { if (param.name && isIdentifier(param.name)) { const name = param.name.escapedText; - return getJSDocTags(param.parent).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name) as JSDocParameterTag[]; + return getJSDocTags(param.parent).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name); } // a binding pattern doesn't have a name, so it's not possible to match it a JSDoc parameter, which is identified by name return undefined; diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index ab07182b8e79c..fa9bf124e5121 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1621,7 +1621,7 @@ Actual: ${stringify(fullActual)}`); const diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); for (const diagnostic of diagnostics) { if (!ts.isString(diagnostic.messageText)) { - let chainedMessage = diagnostic.messageText; + let chainedMessage = diagnostic.messageText; let indentation = " "; while (chainedMessage) { resultString += indentation + chainedMessage.messageText + Harness.IO.newLine(); @@ -3170,24 +3170,23 @@ Actual: ${stringify(fullActual)}`); } private findFile(indexOrName: string | number) { - let result: FourSlashFile; if (typeof indexOrName === "number") { - const index = indexOrName; + const index = indexOrName; if (index >= this.testData.files.length) { throw new Error(`File index (${index}) in openFile was out of range. There are only ${this.testData.files.length} files in this test.`); } else { - result = this.testData.files[index]; + return this.testData.files[index]; } } else if (ts.isString(indexOrName)) { - let name = indexOrName; + let name = indexOrName; // names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name; const availableNames: string[] = []; - result = ts.forEach(this.testData.files, file => { + const result = ts.forEach(this.testData.files, file => { const fn = file.fileName; if (fn) { if (fn === name) { @@ -3200,12 +3199,11 @@ Actual: ${stringify(fullActual)}`); if (!result) { throw new Error(`No test file named "${name}" exists. Available file names are: ${availableNames.join(", ")}`); } + return result; } else { - throw new Error("Unknown argument type"); + return ts.Debug.assertNever(indexOrName); } - - return result; } private getLineColStringAtPosition(position: number) { diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 53f8133b8e510..e35ecba2a04ca 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -57,7 +57,7 @@ var assert: typeof _chai.assert = _chai.assert; } declare var __dirname: string; // Node-specific -var global: NodeJS.Global = Function("return this").call(undefined); +var global: NodeJS.Global = Function("return this").call(undefined); declare var window: {}; declare var XMLHttpRequest: { @@ -767,10 +767,9 @@ namespace Harness { return ts.matchFiles(path, extension, exclude, include, useCaseSensitiveFileNames(), getCurrentDirectory(), depth, path => { const entry = fs.traversePath(path); if (entry && entry.isDirectory()) { - const directory = entry; return { - files: ts.map(directory.getFiles(), f => f.name), - directories: ts.map(directory.getDirectories(), d => d.name) + files: ts.map(entry.getFiles(), f => f.name), + directories: ts.map(entry.getDirectories(), d => d.name) }; } return { files: [], directories: [] }; diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index d24f572d1d51d..c38ab1f3c6df3 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -143,7 +143,7 @@ namespace Harness.LanguageService { public getScriptInfo(fileName: string): ScriptInfo { const fileEntry = this.virtualFileSystem.traversePath(fileName); - return fileEntry && fileEntry.isFile() ? (fileEntry).content : undefined; + return fileEntry && fileEntry.isFile() ? fileEntry.content : undefined; } public addScript(fileName: string, content: string, isRootFile: boolean): void { diff --git a/src/harness/unittests/reuseProgramStructure.ts b/src/harness/unittests/reuseProgramStructure.ts index 454e97b313311..70325831f5129 100644 --- a/src/harness/unittests/reuseProgramStructure.ts +++ b/src/harness/unittests/reuseProgramStructure.ts @@ -165,7 +165,7 @@ namespace ts { export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[]) { if (!newTexts) { - newTexts = (oldProgram).sourceTexts.slice(0); + newTexts = oldProgram.sourceTexts.slice(0); } updater(newTexts); const host = createTestCompilerHost(newTexts, options.target, oldProgram); diff --git a/src/harness/unittests/textChanges.ts b/src/harness/unittests/textChanges.ts index 0a3602ea0b107..e3f67b8c513b5 100644 --- a/src/harness/unittests/textChanges.ts +++ b/src/harness/unittests/textChanges.ts @@ -91,7 +91,7 @@ namespace M } }`; runSingleFileTest("extractMethodLike", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - const statements = ((findChild("foo", sourceFile)).body).statements.slice(1); + const statements = (findChild("foo", sourceFile)).body.statements.slice(1); const newFunction = createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 8d84732f3aa04..e09dff2a6d5dd 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -2560,7 +2560,7 @@ namespace ts.projectSystem { } assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent); assert.equal(e.data.project.getProjectName(), config.path, "project name"); - lastEvent = e; + lastEvent = e; } }); session.executeCommand({ diff --git a/src/harness/virtualFileSystem.ts b/src/harness/virtualFileSystem.ts index 54572814d8ed1..16267a092fce4 100644 --- a/src/harness/virtualFileSystem.ts +++ b/src/harness/virtualFileSystem.ts @@ -42,12 +42,12 @@ namespace Utils { getDirectory(name: string): VirtualDirectory { const entry = this.getFileSystemEntry(name); - return entry.isDirectory() ? entry : undefined; + return entry.isDirectory() ? entry : undefined; } getFile(name: string): VirtualFile { const entry = this.getFileSystemEntry(name); - return entry.isFile() ? entry : undefined; + return entry.isFile() ? entry : undefined; } } @@ -66,7 +66,7 @@ namespace Utils { return directory; } else if (entry.isDirectory()) { - return entry; + return entry; } else { return undefined; @@ -149,7 +149,7 @@ namespace Utils { return undefined; } else if (entry.isDirectory()) { - directory = entry; + directory = entry; } else { return entry; @@ -167,10 +167,9 @@ namespace Utils { getAccessibleFileSystemEntries(path: string) { const entry = this.traversePath(path); if (entry && entry.isDirectory()) { - const directory = entry; return { - files: ts.map(directory.getFiles(), f => f.name), - directories: ts.map(directory.getDirectories(), d => d.name) + files: ts.map(entry.getFiles(), f => f.name), + directories: ts.map(entry.getDirectories(), d => d.name) }; } return { files: [], directories: [] }; diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 3d0d623c6d41a..c525d5a3bc821 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -2026,7 +2026,7 @@ namespace ts.server { } else { configFileErrors = project.getAllProjectErrors(); - this.sendConfigFileDiagEvent(project as ConfiguredProject, fileName); + this.sendConfigFileDiagEvent(project, fileName); } } else { diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index dccf4d3267b19..7757cbf83e3f5 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -765,13 +765,13 @@ namespace ts.server { for (let i = 0; i < splitNodeCount; i++) { splitNodes[i] = new LineNode(); } - let splitNode = splitNodes[0]; + let splitNode = splitNodes[0]; while (nodeIndex < nodeCount) { splitNode.add(nodes[nodeIndex]); nodeIndex++; if (splitNode.children.length === lineCollectionCapacity) { splitNodeIndex++; - splitNode = splitNodes[splitNodeIndex]; + splitNode = splitNodes[splitNodeIndex]; } } for (let i = splitNodes.length - 1; i >= 0; i--) { @@ -785,7 +785,7 @@ namespace ts.server { } this.updateCounts(); for (let i = 0; i < splitNodeCount; i++) { - (splitNodes[i]).updateCounts(); + splitNodes[i].updateCounts(); } return splitNodes; } diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index 26df417f87924..efc27314a9869 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -390,7 +390,7 @@ namespace ts.BreakpointResolver { // If this is a destructuring pattern, set breakpoint in binding pattern if (isBindingPattern(variableDeclaration.name)) { - return spanInBindingPattern(variableDeclaration.name); + return spanInBindingPattern(variableDeclaration.name); } // Breakpoint is possible in variableDeclaration only if there is initialization @@ -420,7 +420,7 @@ namespace ts.BreakpointResolver { function spanInParameterDeclaration(parameter: ParameterDeclaration): TextSpan { if (isBindingPattern(parameter.name)) { // Set breakpoint in binding pattern - return spanInBindingPattern(parameter.name); + return spanInBindingPattern(parameter.name); } else if (canHaveSpanInParameterDeclaration(parameter)) { return textSpan(parameter); @@ -540,10 +540,7 @@ namespace ts.BreakpointResolver { function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node: DestructuringPattern): TextSpan { Debug.assert(node.kind !== SyntaxKind.ArrayBindingPattern && node.kind !== SyntaxKind.ObjectBindingPattern); - const elements: NodeArray = - node.kind === SyntaxKind.ArrayLiteralExpression ? - (node).elements : - (node).properties; + const elements: NodeArray = node.kind === SyntaxKind.ArrayLiteralExpression ? node.elements : (node as ObjectLiteralExpression).properties; const firstBindingElement = forEach(elements, element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined); diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index cb94c2112afbf..de053c2fe8f3b 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -195,7 +195,7 @@ namespace ts.codefix { } function tryDeleteNamedImportBinding(changes: textChanges.ChangeTracker, sourceFile: SourceFile, namedBindings: NamedImportBindings): void { - if ((namedBindings.parent).name) { + if (namedBindings.parent.name) { // Delete named imports while preserving the default import // import d|, * as ns| from './file' // import d|, { a }| from './file' @@ -229,7 +229,7 @@ namespace ts.codefix { } case SyntaxKind.ForOfStatement: - const forOfStatement = varDecl.parent.parent; + const forOfStatement = varDecl.parent.parent; Debug.assert(forOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList); const forOfInitializer = forOfStatement.initializer; changes.replaceNode(sourceFile, forOfInitializer.declarations[0], createObjectLiteral()); @@ -240,7 +240,7 @@ namespace ts.codefix { break; default: - const variableStatement = varDecl.parent.parent; + const variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { changes.deleteNode(sourceFile, variableStatement); } diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 47e23e717d9b5..6a45c66ca816d 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -24,7 +24,7 @@ namespace ts.codefix { return undefined; } - const declaration = declarations[0] as Declaration; + const declaration = declarations[0]; // Clone name to remove leading trivia. const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration)) as PropertyName; const visibilityModifier = createVisibilityModifier(getModifierFlags(declaration)); diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 902764a172977..e17c518361199 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -140,7 +140,7 @@ namespace ts.codefix { case SyntaxKind.Constructor: return true; case SyntaxKind.FunctionExpression: - return !!(declaration as FunctionExpression).name; + return !!declaration.name; } return false; } @@ -497,7 +497,7 @@ namespace ts.codefix { } function inferTypeFromSwitchStatementLabelContext(parent: CaseOrDefaultClause, checker: TypeChecker, usageContext: UsageContext): void { - addCandidateType(usageContext, checker.getTypeAtLocation((parent.parent.parent).expression)); + addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression)); } function inferTypeFromCallExpressionContext(parent: CallExpression | NewExpression, checker: TypeChecker, usageContext: UsageContext): void { diff --git a/src/services/completions.ts b/src/services/completions.ts index 68ec65a1e19f3..7485fbec37a1d 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1068,10 +1068,10 @@ namespace ts.Completions { let attrsType: Type; if ((jsxContainer.kind === SyntaxKind.JsxSelfClosingElement) || (jsxContainer.kind === SyntaxKind.JsxOpeningElement)) { // Cursor is inside a JSX self-closing element or opening element - attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), (jsxContainer).attributes.properties); + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); completionKind = CompletionKind.MemberLike; isNewIdentifierLocation = false; return true; @@ -1429,10 +1429,10 @@ namespace ts.Completions { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; - const typeForObject = typeChecker.getContextualType(objectLikeContainer); + const typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); - existingMembers = (objectLikeContainer).properties; + existingMembers = objectLikeContainer.properties; } else { Debug.assert(objectLikeContainer.kind === SyntaxKind.ObjectBindingPattern); @@ -1461,7 +1461,7 @@ namespace ts.Completions { if (!typeForObject) return false; // In a binding pattern, get only known properties. Everywhere else we will get all possible properties. typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter((symbol) => !(getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.NonPublicAccessibilityModifier)); - existingMembers = (objectLikeContainer).elements; + existingMembers = objectLikeContainer.elements; } } @@ -2073,7 +2073,7 @@ namespace ts.Completions { } if (attr.kind === SyntaxKind.JsxAttribute) { - seenNames.set((attr).name.escapedText, true); + seenNames.set(attr.name.escapedText, true); } } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index b1e6909f093f8..233595c282ec5 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -912,7 +912,7 @@ namespace ts.FindAllReferences.Core { // For `export { foo as bar }`, rename `foo`, but not `bar`. if (!(referenceLocation === propertyName && state.options.isForRename)) { - const exportKind = (referenceLocation as Identifier).originalKeywordKind === ts.SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named; + const exportKind = referenceLocation.originalKeywordKind === ts.SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named; const exportInfo = getExportInfo(referenceSymbol, exportKind, state.checker); Debug.assert(!!exportInfo); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); @@ -1125,7 +1125,7 @@ namespace ts.FindAllReferences.Core { } }); } - else if (isImplementationExpression(body)) { + else if (isImplementationExpression(body)) { addReference(body); } } @@ -1647,10 +1647,10 @@ namespace ts.FindAllReferences.Core { function getNameFromObjectLiteralElement(node: ObjectLiteralElement): string { if (node.name.kind === SyntaxKind.ComputedPropertyName) { - const nameExpression = (node.name).expression; + const nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (isStringOrNumericLiteral(nameExpression)) { - return (nameExpression).text; + return nameExpression.text; } return undefined; } @@ -1728,7 +1728,7 @@ namespace ts.FindAllReferences.Core { function getParentStatementOfVariableDeclaration(node: VariableDeclaration): VariableStatement { if (node.parent && node.parent.parent && node.parent.parent.kind === SyntaxKind.VariableStatement) { Debug.assert(node.parent.kind === SyntaxKind.VariableDeclarationList); - return node.parent.parent; + return node.parent.parent; } } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 22446a98ce272..3ed602d17fbbd 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -200,7 +200,7 @@ namespace ts.formatting { return rangeContainsRange((parent).members, node); case SyntaxKind.ModuleDeclaration: const body = (parent).body; - return body && body.kind === SyntaxKind.ModuleBlock && rangeContainsRange((body).statements, node); + return body && body.kind === SyntaxKind.ModuleBlock && rangeContainsRange(body.statements, node); case SyntaxKind.SourceFile: case SyntaxKind.Block: case SyntaxKind.ModuleBlock: diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 1e6323be9fa0d..f124c444f6d69 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -383,9 +383,8 @@ namespace ts.formatting { return Value.Unknown; } - if (node.parent && isCallOrNewExpression(node.parent) && (node.parent).expression !== node) { - - const fullCallOrNewExpression = (node.parent).expression; + if (node.parent && isCallOrNewExpression(node.parent) && node.parent.expression !== node) { + const fullCallOrNewExpression = node.parent.expression; const startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index d3e57b124deda..a9e2f20272638 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -629,7 +629,7 @@ namespace ts.FindAllReferences { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (const declaration of symbol.declarations) { - if (isExportSpecifier(declaration) && !(declaration as ExportSpecifier).propertyName && !(declaration as ExportSpecifier).parent.parent.moduleSpecifier) { + if (isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { return checker.getExportSpecifierLocalTargetSymbol(declaration); } } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 91774e2290c68..deb6adcb6b628 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -268,9 +268,7 @@ namespace ts.JsDoc { let docParams = ""; for (let i = 0; i < parameters.length; i++) { const currentName = parameters[i].name; - const paramName = currentName.kind === SyntaxKind.Identifier ? - (currentName).escapedText : - "param" + i; + const paramName = currentName.kind === SyntaxKind.Identifier ? currentName.escapedText : "param" + i; if (isJavaScriptFile) { docParams += `${indentationStr} * @param {any} ${paramName}${newLine}`; } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 8449805ee71be..3b5e5ee59babe 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -97,7 +97,7 @@ namespace ts.NavigateTo { containers.unshift(text); } else if (name.kind === SyntaxKind.ComputedPropertyName) { - return tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ true); + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); } else { // Don't know how to add this. @@ -140,7 +140,7 @@ namespace ts.NavigateTo { // portion into the container array. const name = getNameOfDeclaration(declaration); if (name.kind === SyntaxKind.ComputedPropertyName) { - if (!tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ false)) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -181,7 +181,7 @@ namespace ts.NavigateTo { function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { const declaration = rawItem.declaration; - const container = getContainerNode(declaration); + const container = getContainerNode(declaration); const containerName = container && getNameOfDeclaration(container); return { name: rawItem.name, diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 19a74c5af57ca..cdc7b2b186435 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -197,10 +197,10 @@ namespace ts.NavigationBar { const {namedBindings} = importClause; if (namedBindings) { if (namedBindings.kind === SyntaxKind.NamespaceImport) { - addLeafNode(namedBindings); + addLeafNode(namedBindings); } else { - for (const element of (namedBindings).elements) { + for (const element of namedBindings.elements) { addLeafNode(element); } } @@ -475,8 +475,8 @@ namespace ts.NavigationBar { else { const parentNode = node.parent && node.parent.parent; if (parentNode && parentNode.kind === SyntaxKind.VariableStatement) { - if ((parentNode).declarationList.declarations.length > 0) { - const nameIdentifier = (parentNode).declarationList.declarations[0].name; + if (parentNode.declarationList.declarations.length > 0) { + const nameIdentifier = parentNode.declarationList.declarations[0].name; if (nameIdentifier.kind === SyntaxKind.Identifier) { return nameIdentifier.text; } diff --git a/src/services/refactors/annotateWithTypeFromJSDoc.ts b/src/services/refactors/annotateWithTypeFromJSDoc.ts index 6f87332aa9615..3258da4636a51 100644 --- a/src/services/refactors/annotateWithTypeFromJSDoc.ts +++ b/src/services/refactors/annotateWithTypeFromJSDoc.ts @@ -118,7 +118,7 @@ namespace ts.refactor.annotateWithTypeFromJSDoc { case SyntaxKind.Constructor: return createConstructor(decl.decorators, decl.modifiers, parameters, decl.body); case SyntaxKind.FunctionExpression: - return createFunctionExpression(decl.modifiers, decl.asteriskToken, (decl as FunctionExpression).name, typeParameters, parameters, returnType, decl.body); + return createFunctionExpression(decl.modifiers, decl.asteriskToken, decl.name, typeParameters, parameters, returnType, decl.body); case SyntaxKind.ArrowFunction: return createArrowFunction(decl.modifiers, typeParameters, parameters, returnType, decl.equalsGreaterThanToken, decl.body); case SyntaxKind.MethodDeclaration: diff --git a/src/services/refactors/convertFunctionToEs6Class.ts b/src/services/refactors/convertFunctionToEs6Class.ts index 6645f8434b6b4..ddb13c3e04ce7 100644 --- a/src/services/refactors/convertFunctionToEs6Class.ts +++ b/src/services/refactors/convertFunctionToEs6Class.ts @@ -180,8 +180,7 @@ namespace ts.refactor.convertFunctionToES6Class { } // case 2: () => [1,2,3] else { - const expression = arrowFunctionBody as Expression; - bodyBlock = createBlock([createReturn(expression)]); + bodyBlock = createBlock([createReturn(arrowFunctionBody)]); } const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, SyntaxKind.AsyncKeyword)); const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, diff --git a/src/services/refactors/convertToEs6Module.ts b/src/services/refactors/convertToEs6Module.ts index f1f3c16b6bb16..6ed9cbec2ee97 100644 --- a/src/services/refactors/convertToEs6Module.ts +++ b/src/services/refactors/convertToEs6Module.ts @@ -194,7 +194,7 @@ namespace ts.refactor { } function convertVariableStatement(sourceFile: SourceFile, statement: VariableStatement, changes: textChanges.ChangeTracker, checker: TypeChecker, identifiers: Identifiers, target: ScriptTarget): void { - const { declarationList } = statement as VariableStatement; + const { declarationList } = statement; let foundImport = false; const newNodes = flatMap(declarationList.declarations, decl => { const { name, initializer } = decl; @@ -290,14 +290,10 @@ namespace ts.refactor { case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.SpreadAssignment: return undefined; - case SyntaxKind.PropertyAssignment: { - const { name, initializer } = prop as PropertyAssignment; - return !isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); - } - case SyntaxKind.MethodDeclaration: { - const m = prop as MethodDeclaration; - return !isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [createToken(SyntaxKind.ExportKeyword)], m); - } + case SyntaxKind.PropertyAssignment: + return !isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); + case SyntaxKind.MethodDeclaration: + return !isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [createToken(SyntaxKind.ExportKeyword)], prop); default: Debug.assertNever(prop); } diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index bf410ab27a9cd..65c9fd6268c3e 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -223,7 +223,7 @@ namespace ts.refactor.extractSymbol { return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } const statements: Statement[] = []; - for (const statement of (start.parent).statements) { + for (const statement of start.parent.statements) { if (statement === start || statements.length) { const errors = checkNode(statement); if (errors) { @@ -1476,7 +1476,7 @@ namespace ts.refactor.extractSymbol { } const seenUsages = createMap(); - const target = isReadonlyArray(targetRange.range) ? createBlock(targetRange.range) : targetRange.range; + const target = isReadonlyArray(targetRange.range) ? createBlock(targetRange.range) : targetRange.range; const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; const inGenericContext = isInGenericContext(unmodifiedNode); @@ -1681,9 +1681,9 @@ namespace ts.refactor.extractSymbol { // if we get here this means that we are trying to handle 'write' and 'read' was already processed // walk scopes and update existing records. for (const perScope of usagesPerScope) { - const prevEntry = perScope.usages.get(identifier.text as string); + const prevEntry = perScope.usages.get(identifier.text); if (prevEntry) { - perScope.usages.set(identifier.text as string, { usage, symbol, node: identifier }); + perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); } } return symbolId; @@ -1730,7 +1730,7 @@ namespace ts.refactor.extractSymbol { } } else { - usagesPerScope[i].usages.set(identifier.text as string, { usage, symbol, node: identifier }); + usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); } } } diff --git a/src/services/services.ts b/src/services/services.ts index b5d6f0ec2a655..991b6c1060652 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -728,7 +728,7 @@ namespace ts { } if (name.kind === SyntaxKind.ComputedPropertyName) { - const expr = (name).expression; + const expr = name.expression; if (expr.kind === SyntaxKind.PropertyAccessExpression) { return (expr).name.text; } @@ -832,10 +832,10 @@ namespace ts { // import {a, b as B} from "mod"; if (importClause.namedBindings) { if (importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { - addDeclaration(importClause.namedBindings); + addDeclaration(importClause.namedBindings); } else { - forEach((importClause.namedBindings).elements, visit); + forEach(importClause.namedBindings.elements, visit); } } } @@ -2218,7 +2218,7 @@ namespace ts { case SyntaxKind.Identifier: return isObjectLiteralElement(node.parent) && (node.parent.parent.kind === SyntaxKind.ObjectLiteralExpression || node.parent.parent.kind === SyntaxKind.JsxAttributes) && - (node.parent).name === node ? node.parent as ObjectLiteralElement : undefined; + node.parent.name === node ? node.parent : undefined; } return undefined; } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index aa30ba0de6fc5..48e35d831fb7b 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -57,14 +57,9 @@ namespace ts.SignatureHelp { } // See if we can find some symbol with the call expression name that has call signatures. - const callExpression = argumentInfo.invocation; + const callExpression = argumentInfo.invocation; const expression = callExpression.expression; - const name = expression.kind === SyntaxKind.Identifier - ? expression - : expression.kind === SyntaxKind.PropertyAccessExpression - ? (expression).name - : undefined; - + const name = isIdentifier(expression) ? expression : isPropertyAccessExpression(expression) ? expression.name : undefined; if (!name || !name.escapedText) { return undefined; } @@ -160,7 +155,7 @@ namespace ts.SignatureHelp { } else if (node.parent.kind === SyntaxKind.TemplateSpan && node.parent.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) { const templateSpan = node.parent; - const templateExpression = templateSpan.parent; + const templateExpression = templateSpan.parent; const tagExpression = templateExpression.parent; Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression); @@ -272,7 +267,7 @@ namespace ts.SignatureHelp { // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. const argumentCount = tagExpression.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral ? 1 - : (tagExpression.template).templateSpans.length + 1; + : tagExpression.template.templateSpans.length + 1; if (argumentIndex !== 0) { Debug.assertLessThan(argumentIndex, argumentCount); @@ -314,7 +309,7 @@ namespace ts.SignatureHelp { // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === SyntaxKind.TemplateExpression) { - const lastSpan = lastOrUndefined((template).templateSpans); + const lastSpan = lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 387d027d999f9..135e906143fbe 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -146,13 +146,13 @@ namespace ts.SymbolDisplay { // try get the call/construct signature from the type if it matches let callExpressionLike: CallExpression | NewExpression | JsxOpeningLikeElement; if (isCallOrNewExpression(location)) { - callExpressionLike = location; + callExpressionLike = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { callExpressionLike = location.parent; } else if (location.parent && isJsxOpeningLikeElement(location.parent) && isFunctionLike(symbol.valueDeclaration)) { - callExpressionLike = location.parent; + callExpressionLike = location.parent; } if (callExpressionLike) { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 8df8a902734d9..263ac0f4c3bb3 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -131,7 +131,7 @@ namespace ts { while (node.parent.kind === SyntaxKind.QualifiedName) { node = node.parent; } - return isInternalModuleImportEqualsDeclaration(node.parent) && (node.parent).moduleReference === node; + return isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } function isNamespaceReference(node: Node): boolean { diff --git a/tslint.json b/tslint.json index b801df720f2e2..bd06724edb8fc 100644 --- a/tslint.json +++ b/tslint.json @@ -2,6 +2,8 @@ "extends": "tslint:latest", "rulesDirectory": "built/local/tslint/rules", "rules": { + "no-unnecessary-type-assertion-2": true, + "array-type": [true, "array"], "ban-types": { "options": [ From 45d52f5d0c90043ccc6b00a7d00692005a67ad7b Mon Sep 17 00:00:00 2001 From: andy-ms Date: Fri, 16 Feb 2018 16:52:07 -0800 Subject: [PATCH 2/4] Fix type error --- src/compiler/parser.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 8426c8de2afe8..70ddb7b791df1 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -5253,7 +5253,7 @@ namespace ts { if (node.decorators || node.modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - const missing = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const missing = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; From ddba5007b506765b241b495a05a4bbf647c9a092 Mon Sep 17 00:00:00 2001 From: andy-ms Date: Fri, 16 Feb 2018 17:51:37 -0800 Subject: [PATCH 3/4] Fix tsconfig.json --- scripts/tslint/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/tslint/tsconfig.json b/scripts/tslint/tsconfig.json index cdb63febcc758..9d348658394f0 100644 --- a/scripts/tslint/tsconfig.json +++ b/scripts/tslint/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "lib": "es6", + "lib": ["es6"], "noImplicitAny": true, "noImplicitReturns": true, "noImplicitThis": true, From 456671fe18828a80c3ad265ceaf8bc3e67d90616 Mon Sep 17 00:00:00 2001 From: andy-ms Date: Fri, 16 Feb 2018 18:16:25 -0800 Subject: [PATCH 4/4] Add --format back --- Gulpfile.ts | 2 +- Jakefile.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gulpfile.ts b/Gulpfile.ts index 7633d4969671a..e8bd7a990fe01 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -1111,7 +1111,7 @@ function spawnLintWorker(files: {path: string}[], callback: (failures: number) = gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => { if (fold.isTravis()) console.log(fold.start("lint")); for (const project of ["scripts/tslint/tsconfig.json", "src/tsconfig-base.json"]) { - const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters`; + const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`; console.log("Linting: " + cmd); child_process.execSync(cmd, { stdio: [0, 1, 2] }); } diff --git a/Jakefile.js b/Jakefile.js index 13da0d9918587..9935b6b0f1320 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -1303,7 +1303,7 @@ desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex task("lint", ["build-rules"], () => { if (fold.isTravis()) console.log(fold.start("lint")); function lint(project, cb) { - const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters`; + const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`; console.log("Linting: " + cmd); jake.exec([cmd], { interactive: true, windowsVerbatimArguments: true }, cb); }