Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

no-unnecessary-type-assertion: Don't check ! if --strictNullChecks is not enabled #3724

Merged
merged 4 commits into from Jun 15, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/rules/noUnnecessaryTypeAssertionRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,28 @@ export class Rule extends Lint.Rules.TypedRule {
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()));
return this.applyWithWalker(new Walker(
sourceFile, this.ruleName, this.ruleArguments, program.getTypeChecker(), !!program.getCompilerOptions().strictNullChecks));
}
}

class Walker extends Lint.AbstractWalker<string[]> {
constructor(sourceFile: ts.SourceFile, ruleName: string, options: string[], private readonly checker: ts.TypeChecker) {
constructor(
sourceFile: ts.SourceFile,
ruleName: string,
options: string[],
private readonly checker: ts.TypeChecker,
private readonly strictNullChecks: boolean) {
super(sourceFile, ruleName, options);
}

public walk(sourceFile: ts.SourceFile) {
const cb = (node: ts.Node): void => {
switch (node.kind) {
case ts.SyntaxKind.NonNullExpression:
this.checkNonNullAssertion(node as ts.NonNullExpression);
if (this.strictNullChecks) {
this.checkNonNullAssertion(node as ts.NonNullExpression);
}
break;
case ts.SyntaxKind.TypeAssertionExpression:
case ts.SyntaxKind.AsExpression:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare const x: string | undefined;
x!;

declare const y: string;
y as string;
~~~~~~~~~~~ [This assertion is unnecessary since it does not change the type of the expression.]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"no-unnecessary-type-assertion": true
}
}