Apply 'no-unnecessary-type-assertion' lint rule (#22005)

* Apply 'no-unnecessary-type-assertion' lint rule

* Fix type error

* Fix tsconfig.json

* Add --format back
This commit is contained in:
Andy 2018-02-16 18:38:00 -08:00 committed by GitHub
parent 8e078b9fde
commit b3edc8f9f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
52 changed files with 495 additions and 451 deletions

View File

@ -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 --format autolinkableStylish`;
console.log("Linting: " + cmd);
child_process.execSync(cmd, { stdio: [0, 1, 2] });
}
if (fold.isTravis()) console.log(fold.end("lint"));
});

View File

@ -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 --format autolinkableStylish`;
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();
});
}));
});

View File

@ -27,7 +27,7 @@ function walk(ctx: Lint.WalkContext<void>): 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>): 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;
}

View File

@ -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<string[]> {
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()));
}
}
}

View File

@ -1,5 +1,6 @@
{
"compilerOptions": {
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,

View File

@ -264,7 +264,7 @@ namespace ts {
return (isGlobalScopeAugmentation(<ModuleDeclaration>node) ? "__global" : `"${moduleName}"`) as __String;
}
if (name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (<ComputedPropertyName>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)) {
(<FlowStart>currentFlow).container = <FunctionExpression | ArrowFunction | MethodDeclaration>node;
currentFlow.container = <FunctionExpression | ArrowFunction | MethodDeclaration>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(<Expression>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, <SwitchStatement>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 (<ObjectLiteralExpression>node).properties) {
if (p.kind === SyntaxKind.PropertyAssignment) {
bindDestructuringTargetFlow((<PropertyAssignment>p).initializer);
bindDestructuringTargetFlow(p.initializer);
}
else if (p.kind === SyntaxKind.ShorthandPropertyAssignment) {
bindAssignmentTargetFlow((<ShorthandPropertyAssignment>p).name);
bindAssignmentTargetFlow(p.name);
}
else if (p.kind === SyntaxKind.SpreadAssignment) {
bindAssignmentTargetFlow((<SpreadAssignment>p).expression);
bindAssignmentTargetFlow(p.expression);
}
}
}
@ -1572,7 +1569,7 @@ namespace ts {
}
function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean {
const body = node.kind === SyntaxKind.SourceFile ? node : (<ModuleDeclaration>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 (<BlockLike>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(<FunctionDeclaration>node);
checkStrictModeFunctionName(node);
if (inStrictMode) {
checkStrictModeFunctionDeclaration(node);
bindBlockScopedDeclaration(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
}
else {
declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
declareSymbolAndAddToSymbolTable(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
}
}

View File

@ -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;
}

File diff suppressed because it is too large Load Diff

View File

@ -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(<NamespaceImport>namedBindings);
return resolver.isDeclarationVisible(namedBindings);
}
else {
return forEach((<NamedImports>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, (<NamespaceImport>node.importClause.namedBindings).name);
writeTextOfNode(currentText, node.importClause.namedBindings.name);
}
else {
write("{ ");
emitCommaList((<NamedImports>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 = (<ModuleDeclaration>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(<BindingPattern>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(<ParameterDeclaration>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(<BindingPattern>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(<BindingPattern>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(<BindingPattern>bindingElement.name);
emitBindingPattern(bindingElement.name);
}
else {
Debug.assert(bindingElement.name.kind === SyntaxKind.Identifier);

View File

@ -951,7 +951,7 @@ namespace ts {
function emitEntityName(node: EntityName) {
if (node.kind === SyntaxKind.Identifier) {
emitExpression(<Identifier>node);
emitExpression(node);
}
else {
emit(node);
@ -1709,7 +1709,7 @@ namespace ts {
emit(node);
}
else {
emitExpression(<Expression>node);
emitExpression(node);
}
}
}
@ -2068,7 +2068,7 @@ namespace ts {
function emitModuleReference(node: ModuleReference) {
if (node.kind === SyntaxKind.Identifier) {
emitExpression(<Identifier>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<true>();
for (const sourceFile of (sourceFileOrBundle as Bundle).sourceFiles) {
for (const sourceFile of sourceFileOrBundle.sourceFiles) {
setSourceFile(sourceFile);
emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
}

View File

@ -644,7 +644,7 @@ namespace ts {
}
export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <FunctionTypeNode>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<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <ConstructorTypeNode>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 = <YieldExpression>createSynthesizedNode(SyntaxKind.YieldExpression);
node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === SyntaxKind.AsteriskToken ? <AsteriskToken>asteriskTokenOrExpression : undefined;
node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== SyntaxKind.AsteriskToken ? <Expression>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, <AccessorDeclaration>property, receiver, node.multiLine);
return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine);
case SyntaxKind.PropertyAssignment:
return createExpressionForPropertyAssignment(<PropertyAssignment>property, receiver);
return createExpressionForPropertyAssignment(property, receiver);
case SyntaxKind.ShorthandPropertyAssignment:
return createExpressionForShorthandPropertyAssignment(<ShorthandPropertyAssignment>property, receiver);
return createExpressionForShorthandPropertyAssignment(property, receiver);
case SyntaxKind.MethodDeclaration:
return createExpressionForMethodDeclaration(<MethodDeclaration>property, receiver);
return createExpressionForMethodDeclaration(property, receiver);
}
}
@ -4065,13 +4065,13 @@ namespace ts {
export function parenthesizePostfixOperand(operand: Expression) {
return isLeftHandSideExpression(operand)
? <LeftHandSideExpression>operand
? operand
: setTextRange(createParen(operand), operand);
}
export function parenthesizePrefixOperand(operand: Expression) {
return isUnaryExpression(operand)
? <UnaryExpression>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(<Expression>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 && (<ImportDeclaration>node).importClause) {
if (node.kind === SyntaxKind.ImportDeclaration && node.importClause) {
return getGeneratedNameForNode(node);
}
if (node.kind === SyntaxKind.ExportDeclaration && (<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 <ObjectBindingPattern | ArrayBindingPattern | Identifier>bindingElement.name;
return bindingElement.name;
}
if (isObjectLiteralElementLike(bindingElement)) {
@ -4556,12 +4556,12 @@ namespace ts {
case SyntaxKind.Parameter:
case SyntaxKind.BindingElement:
// `...` in `let [...a] = ...`
return (<ParameterDeclaration | BindingElement>bindingElement).dotDotDotToken;
return bindingElement.dotDotDotToken;
case SyntaxKind.SpreadElement:
case SyntaxKind.SpreadAssignment:
// `...` in `[...a] = ...`
return <SpreadElement | SpreadAssignment>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>bindingElement).propertyName) {
const propertyName = (<BindingElement>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 ((<PropertyAssignment>bindingElement).name) {
const propertyName = (<PropertyAssignment>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 (<SpreadAssignment>bindingElement).name;
return bindingElement.name;
}
const target = getTargetOfBindingOrAssignmentElement(bindingElement);
@ -4639,7 +4639,7 @@ namespace ts {
Debug.assertNode(element.name, isIdentifier);
return setOriginalNode(setTextRange(createSpread(<Identifier>element.name), element), element);
}
const expression = convertToAssignmentElementTarget(<ObjectBindingPattern | ArrayBindingPattern | Identifier>element.name);
const expression = convertToAssignmentElementTarget(element.name);
return element.initializer
? setOriginalNode(
setTextRange(
@ -4661,7 +4661,7 @@ namespace ts {
return setOriginalNode(setTextRange(createSpreadAssignment(<Identifier>element.name), element), element);
}
if (element.propertyName) {
const expression = convertToAssignmentElementTarget(<ObjectBindingPattern | ArrayBindingPattern | Identifier>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 <ObjectLiteralExpression>node;
return node;
}
export function convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern) {
@ -4708,7 +4708,7 @@ namespace ts {
);
}
Debug.assertNode(node, isArrayLiteralExpression);
return <ArrayLiteralExpression>node;
return node;
}
export function convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression {
@ -4717,6 +4717,6 @@ namespace ts {
}
Debug.assertNode(node, isExpression);
return <Expression>node;
return node;
}
}

View File

@ -690,7 +690,7 @@ namespace ts {
// Prime the scanner.
nextToken();
if (token() === SyntaxKind.EndOfFileToken) {
sourceFile.endOfFileToken = <EndOfFileToken>parseTokenNode();
sourceFile.endOfFileToken = parseTokenNode<EndOfFileToken>();
}
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 = <MethodDeclaration>node;
const nameIsConstructor = methodDeclaration.name.kind === SyntaxKind.Identifier &&
(<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, <BinaryOperatorToken>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, <BinaryOperatorToken>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 = <JsxSelfClosingElement>opening;
result = opening;
}
// If the user writes the invalid code '<div></div><div></div>' 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 = <BinaryOperatorToken>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 <JsxElement><Node>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 = <Statement>createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected);
const missing = createMissingNode<Statement>(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected);
missing.pos = node.pos;
missing.decorators = node.decorators;
missing.modifiers = node.modifiers;

View File

@ -812,7 +812,7 @@ namespace ts {
if (!result) {
// There were no unresolved/ambient resolutions.
Debug.assert(resolutions.length === moduleNames.length);
return <ResolvedModuleFull[]>resolutions;
return resolutions;
}
let j = 0;

View File

@ -1995,7 +1995,7 @@ namespace ts {
// If we are here it is because this is a destructuring assignment.
if (isDestructuringAssignment(node)) {
return flattenDestructuringAssignment(
<DestructuringAssignment>node,
node,
visitor,
context,
FlattenLevel.All,
@ -2023,7 +2023,7 @@ namespace ts {
);
}
else {
assignment = createBinary(<Identifier>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((<Identifier>node));
state.hoistedLocalVariables.push(node);
}
else {
for (const element of (<BindingPattern>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) ? (<Block>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 = <IterationStatement>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, <AccessorDeclaration>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(<MethodDeclaration>property, receiver, node, node.multiLine));
expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
break;
case SyntaxKind.PropertyAssignment:
expressions.push(transformPropertyAssignmentToExpression(<PropertyAssignment>property, receiver, node.multiLine));
expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
break;
case SyntaxKind.ShorthandPropertyAssignment:
expressions.push(transformShorthandPropertyAssignmentToExpression(<ShorthandPropertyAssignment>property, receiver, node.multiLine));
expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
break;
default:

View File

@ -183,7 +183,7 @@ namespace ts {
: visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, visitor, isExpression),
visitNode((<ForStatement>node).statement, asyncBodyVisitor, isStatement, liftToBlock)
visitNode(node.statement, asyncBodyVisitor, isStatement, liftToBlock)
);
}

View File

@ -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));

View File

@ -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 = <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)
]
)
);

View File

@ -57,19 +57,19 @@ namespace ts {
function transformJsxChildToExpression(node: JsxChild): Expression {
switch (node.kind) {
case SyntaxKind.JsxText:
return visitJsxText(<JsxText>node);
return visitJsxText(node);
case SyntaxKind.JsxExpression:
return visitJsxExpression(<JsxExpression>node);
return visitJsxExpression(node);
case SyntaxKind.JsxElement:
return visitJsxElement(<JsxElement>node, /*isChild*/ true);
return visitJsxElement(node, /*isChild*/ true);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ true);
return visitJsxSelfClosingElement(node, /*isChild*/ true);
case SyntaxKind.JsxFragment:
return visitJsxFragment(<JsxFragment>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((<StringLiteral>node).text) || (<StringLiteral>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(<JsxExpression>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((<JsxElement>node).openingElement);
return getTagName(node.openingElement);
}
else {
const name = (<JsxOpeningLikeElement>node).tagName;
const name = node.tagName;
if (isIdentifier(name) && isIntrinsicJsxName(name.escapedText)) {
return createLiteral(idText(name));
}

View File

@ -533,7 +533,7 @@ namespace ts {
}
if (isImportCall(node)) {
return visitImportCallExpression(<ImportCall>node);
return visitImportCallExpression(node);
}
else {
return visitEachChild(node, importCallExpressionVisitor, context);

View File

@ -343,13 +343,12 @@ namespace ts {
continue;
}
const exportDecl = <ExportDeclaration>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 (!(<ImportDeclaration>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 ((<ExportDeclaration>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 (<ExportDeclaration>entry).exportClause.elements) {
for (const e of entry.exportClause.elements) {
properties.push(
createPropertyAssignment(
createLiteral(idText(e.name)),

View File

@ -242,13 +242,13 @@ namespace ts {
}
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
return visitImportDeclaration(node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
return visitImportEqualsDeclaration(node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
return visitExportAssignment(node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>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(<Identifier>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(<QualifiedName>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((<ComputedPropertyName>name).expression)
return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression)
? getGeneratedNameForNode(name)
: (<ComputedPropertyName>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((<ModuleBlock>body).statements, namespaceElementVisitor, isStatement)));
statementsLocation = (<ModuleBlock>body).statements;
statementsLocation = body.statements;
blockLocation = body;
}
else {
@ -3547,9 +3547,7 @@ namespace ts {
return undefined;
}
return isPropertyAccessExpression(node) || isElementAccessExpression(node)
? resolver.getConstantValue(<PropertyAccessExpression | ElementAccessExpression>node)
: undefined;
return isPropertyAccessExpression(node) || isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
}
}

View File

@ -904,11 +904,10 @@ namespace ts {
return;
default:
if (isFunctionLike(node)) {
const name = (<FunctionLikeDeclaration>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((<ComputedPropertyName>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 (<TaggedTemplateExpression>node).tag;
switch (node.kind) {
case SyntaxKind.TaggedTemplateExpression:
return node.tag;
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxSelfClosingElement:
return node.tagName;
default:
return node.expression;
}
else if (isJsxOpeningLikeElement(node)) {
return node.tagName;
}
// Will either be a CallExpression, NewExpression, or Decorator.
return (<CallExpression | Decorator>node).expression;
}
export function nodeCanBeDecorated(node: ClassDeclaration): true;
@ -1559,7 +1558,7 @@ namespace ts {
if (node.kind === SyntaxKind.ImportEqualsDeclaration) {
const reference = (<ImportEqualsDeclaration>node).moduleReference;
if (reference.kind === SyntaxKind.ExternalModuleReference) {
return (<ExternalModuleReference>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 <ImportEqualsDeclaration>node;
}
const importClause = (<ImportDeclaration>node).importClause;
if (importClause && importClause.namedBindings && importClause.namedBindings.kind === SyntaxKind.NamespaceImport) {
return <NamespaceImport>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
&& (<ImportDeclaration>node).importClause
&& !!(<ImportDeclaration>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((<ComputedPropertyName>name).expression) &&
!isWellKnownSymbolSyntactically((<ComputedPropertyName>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<JSDocParameterTag> | 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;

View File

@ -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 = <ts.DiagnosticMessageChain>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 = <number>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 = <string>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) {

View File

@ -57,7 +57,7 @@ var assert: typeof _chai.assert = _chai.assert;
}
declare var __dirname: string; // Node-specific
var global: NodeJS.Global = <any>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 = <Utils.VirtualDirectory>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: [] };

View File

@ -143,7 +143,7 @@ namespace Harness.LanguageService {
public getScriptInfo(fileName: string): ScriptInfo {
const fileEntry = this.virtualFileSystem.traversePath(fileName);
return fileEntry && fileEntry.isFile() ? (<Utils.VirtualFile>fileEntry).content : undefined;
return fileEntry && fileEntry.isFile() ? fileEntry.content : undefined;
}
public addScript(fileName: string, content: string, isRootFile: boolean): void {

View File

@ -165,7 +165,7 @@ namespace ts {
export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray<string>, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[]) {
if (!newTexts) {
newTexts = (<ProgramWithSourceTexts>oldProgram).sourceTexts.slice(0);
newTexts = oldProgram.sourceTexts.slice(0);
}
updater(newTexts);
const host = createTestCompilerHost(newTexts, options.target, oldProgram);

View File

@ -91,7 +91,7 @@ namespace M
}
}`;
runSingleFileTest("extractMethodLike", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => {
const statements = (<Block>(<FunctionDeclaration>findChild("foo", sourceFile)).body).statements.slice(1);
const statements = (<FunctionDeclaration>findChild("foo", sourceFile)).body.statements.slice(1);
const newFunction = createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,

View File

@ -2560,7 +2560,7 @@ namespace ts.projectSystem {
}
assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent);
assert.equal(e.data.project.getProjectName(), config.path, "project name");
lastEvent = <server.ProjectLanguageServiceStateEvent>e;
lastEvent = e;
}
});
session.executeCommand(<protocol.OpenRequest>{

View File

@ -42,12 +42,12 @@ namespace Utils {
getDirectory(name: string): VirtualDirectory {
const entry = this.getFileSystemEntry(name);
return entry.isDirectory() ? <VirtualDirectory>entry : undefined;
return entry.isDirectory() ? entry : undefined;
}
getFile(name: string): VirtualFile {
const entry = this.getFileSystemEntry(name);
return entry.isFile() ? <VirtualFile>entry : undefined;
return entry.isFile() ? entry : undefined;
}
}
@ -66,7 +66,7 @@ namespace Utils {
return directory;
}
else if (entry.isDirectory()) {
return <VirtualDirectory>entry;
return entry;
}
else {
return undefined;
@ -149,7 +149,7 @@ namespace Utils {
return undefined;
}
else if (entry.isDirectory()) {
directory = <VirtualDirectory>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 = <VirtualDirectory>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: [] };

View File

@ -2026,7 +2026,7 @@ namespace ts.server {
}
else {
configFileErrors = project.getAllProjectErrors();
this.sendConfigFileDiagEvent(project as ConfiguredProject, fileName);
this.sendConfigFileDiagEvent(project, fileName);
}
}
else {

View File

@ -765,13 +765,13 @@ namespace ts.server {
for (let i = 0; i < splitNodeCount; i++) {
splitNodes[i] = new LineNode();
}
let splitNode = <LineNode>splitNodes[0];
let splitNode = splitNodes[0];
while (nodeIndex < nodeCount) {
splitNode.add(nodes[nodeIndex]);
nodeIndex++;
if (splitNode.children.length === lineCollectionCapacity) {
splitNodeIndex++;
splitNode = <LineNode>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++) {
(<LineNode>splitNodes[i]).updateCounts();
splitNodes[i].updateCounts();
}
return splitNodes;
}

View File

@ -390,7 +390,7 @@ namespace ts.BreakpointResolver {
// If this is a destructuring pattern, set breakpoint in binding pattern
if (isBindingPattern(variableDeclaration.name)) {
return spanInBindingPattern(<BindingPattern>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(<BindingPattern>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<Expression | ObjectLiteralElement> =
node.kind === SyntaxKind.ArrayLiteralExpression ?
(<ArrayLiteralExpression>node).elements :
(<ObjectLiteralExpression>node).properties;
const elements: NodeArray<Expression | ObjectLiteralElement> = node.kind === SyntaxKind.ArrayLiteralExpression ? node.elements : (node as ObjectLiteralExpression).properties;
const firstBindingElement = forEach(elements,
element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined);

View File

@ -195,7 +195,7 @@ namespace ts.codefix {
}
function tryDeleteNamedImportBinding(changes: textChanges.ChangeTracker, sourceFile: SourceFile, namedBindings: NamedImportBindings): void {
if ((<ImportClause>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 = <ForOfStatement>varDecl.parent.parent;
const forOfStatement = varDecl.parent.parent;
Debug.assert(forOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList);
const forOfInitializer = <VariableDeclarationList>forOfStatement.initializer;
changes.replaceNode(sourceFile, forOfInitializer.declarations[0], createObjectLiteral());
@ -240,7 +240,7 @@ namespace ts.codefix {
break;
default:
const variableStatement = <VariableStatement>varDecl.parent.parent;
const variableStatement = varDecl.parent.parent;
if (variableStatement.declarationList.declarations.length === 1) {
changes.deleteNode(sourceFile, variableStatement);
}

View File

@ -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));

View File

@ -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((<SwitchStatement>parent.parent.parent).expression));
addCandidateType(usageContext, checker.getTypeAtLocation(parent.parent.parent.expression));
}
function inferTypeFromCallExpressionContext(parent: CallExpression | NewExpression, checker: TypeChecker, usageContext: UsageContext): void {

View File

@ -1082,10 +1082,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(<JsxOpeningLikeElement>jsxContainer);
attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer);
if (attrsType) {
symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), (<JsxOpeningLikeElement>jsxContainer).attributes.properties);
symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties);
completionKind = CompletionKind.MemberLike;
isNewIdentifierLocation = false;
return true;
@ -1443,10 +1443,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(<ObjectLiteralExpression>objectLikeContainer);
const typeForObject = typeChecker.getContextualType(objectLikeContainer);
if (!typeForObject) return false;
typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false);
existingMembers = (<ObjectLiteralExpression>objectLikeContainer).properties;
existingMembers = objectLikeContainer.properties;
}
else {
Debug.assert(objectLikeContainer.kind === SyntaxKind.ObjectBindingPattern);
@ -1475,7 +1475,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 = (<ObjectBindingPattern>objectLikeContainer).elements;
existingMembers = objectLikeContainer.elements;
}
}
@ -2087,7 +2087,7 @@ namespace ts.Completions {
}
if (attr.kind === SyntaxKind.JsxAttribute) {
seenNames.set((<JsxAttribute>attr).name.escapedText, true);
seenNames.set(attr.name.escapedText, true);
}
}

View File

@ -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(<Expression>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 = (<ComputedPropertyName>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 (<LiteralExpression>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 <VariableStatement>node.parent.parent;
return node.parent.parent;
}
}

View File

@ -200,7 +200,7 @@ namespace ts.formatting {
return rangeContainsRange((<InterfaceDeclaration>parent).members, node);
case SyntaxKind.ModuleDeclaration:
const body = (<ModuleDeclaration>parent).body;
return body && body.kind === SyntaxKind.ModuleBlock && rangeContainsRange((<ModuleBlock>body).statements, node);
return body && body.kind === SyntaxKind.ModuleBlock && rangeContainsRange(body.statements, node);
case SyntaxKind.SourceFile:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:

View File

@ -383,9 +383,8 @@ namespace ts.formatting {
return Value.Unknown;
}
if (node.parent && isCallOrNewExpression(node.parent) && (<CallExpression>node.parent).expression !== node) {
const fullCallOrNewExpression = (<CallExpression | NewExpression>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) {

View File

@ -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);
}
}

View File

@ -269,9 +269,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 ?
(<Identifier>currentName).escapedText :
"param" + i;
const paramName = currentName.kind === SyntaxKind.Identifier ? currentName.escapedText : "param" + i;
if (isJavaScriptFile) {
docParams += `${indentationStr} * @param {any} ${paramName}${newLine}`;
}

View File

@ -97,7 +97,7 @@ namespace ts.NavigateTo {
containers.unshift(text);
}
else if (name.kind === SyntaxKind.ComputedPropertyName) {
return tryAddComputedPropertyName((<ComputedPropertyName>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((<ComputedPropertyName>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 = <Declaration>getContainerNode(declaration);
const container = getContainerNode(declaration);
const containerName = container && getNameOfDeclaration(container);
return {
name: rawItem.name,

View File

@ -197,10 +197,10 @@ namespace ts.NavigationBar {
const {namedBindings} = importClause;
if (namedBindings) {
if (namedBindings.kind === SyntaxKind.NamespaceImport) {
addLeafNode(<NamespaceImport>namedBindings);
addLeafNode(namedBindings);
}
else {
for (const element of (<NamedImports>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 ((<VariableStatement>parentNode).declarationList.declarations.length > 0) {
const nameIdentifier = (<VariableStatement>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;
}

View File

@ -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:

View File

@ -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,

View File

@ -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);
}

View File

@ -223,7 +223,7 @@ namespace ts.refactor.extractSymbol {
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
}
const statements: Statement[] = [];
for (const statement of (<BlockLike>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<Usage>();
const target = isReadonlyArray(targetRange.range) ? createBlock(<Statement[]>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 });
}
}
}

View File

@ -728,7 +728,7 @@ namespace ts {
}
if (name.kind === SyntaxKind.ComputedPropertyName) {
const expr = (<ComputedPropertyName>name).expression;
const expr = name.expression;
if (expr.kind === SyntaxKind.PropertyAccessExpression) {
return (<PropertyAccessExpression>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(<NamespaceImport>importClause.namedBindings);
addDeclaration(importClause.namedBindings);
}
else {
forEach((<NamedImports>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) &&
(<ObjectLiteralElement>node.parent).name === node ? node.parent as ObjectLiteralElement : undefined;
node.parent.name === node ? node.parent : undefined;
}
return undefined;
}

View File

@ -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 = <CallExpression>argumentInfo.invocation;
const callExpression = argumentInfo.invocation;
const expression = callExpression.expression;
const name = expression.kind === SyntaxKind.Identifier
? <Identifier>expression
: expression.kind === SyntaxKind.PropertyAccessExpression
? (<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 = <TemplateSpan>node.parent;
const templateExpression = <TemplateExpression>templateSpan.parent;
const templateExpression = templateSpan.parent;
const tagExpression = <TaggedTemplateExpression>templateExpression.parent;
Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression);
@ -270,7 +265,6 @@ namespace ts.SignatureHelp {
function getArgumentListInfoForTemplate(tagExpression: TaggedTemplateExpression, argumentIndex: number, sourceFile: SourceFile): ArgumentListInfo {
// argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument.
const argumentCount = isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1;
if (argumentIndex !== 0) {
Debug.assertLessThan(argumentIndex, argumentCount);
}
@ -311,7 +305,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((<TemplateExpression>template).templateSpans);
const lastSpan = lastOrUndefined(template.templateSpans);
if (lastSpan.literal.getFullWidth() === 0) {
applicableSpanEnd = skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
}

View File

@ -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 = <CallExpression | NewExpression>location;
callExpressionLike = location;
}
else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) {
callExpressionLike = <CallExpression | NewExpression>location.parent;
}
else if (location.parent && isJsxOpeningLikeElement(location.parent) && isFunctionLike(symbol.valueDeclaration)) {
callExpressionLike = <JsxOpeningLikeElement>location.parent;
callExpressionLike = location.parent;
}
if (callExpressionLike) {

View File

@ -131,7 +131,7 @@ namespace ts {
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
return isInternalModuleImportEqualsDeclaration(node.parent) && (<ImportEqualsDeclaration>node.parent).moduleReference === node;
return isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
}
function isNamespaceReference(node: Node): boolean {

View File

@ -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": [