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

no-unsafe-any: allow truthyness and falsyness checks #3008

Merged
merged 2 commits into from
Jul 7, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
no-unsafe-any: allow truthyness and falsyness checks
[bugfix] `no-unsafe-any`: allow truthyness and falsyness checks
Fixes: #2981
  • Loading branch information
ajafff committed Jul 6, 2017
commit c5ec2e0ab753368d91f48e38ee364e485a8e3b91
26 changes: 26 additions & 0 deletions src/rules/noUnsafeAnyRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {

case ts.SyntaxKind.Parameter: {
const { type, initializer } = node as ts.ParameterDeclaration;
// TODO handle destructuring
if (initializer !== undefined) {
return cb(initializer, /*anyOk*/ type !== undefined && type.kind === ts.SyntaxKind.AnyKeyword);
}
Expand Down Expand Up @@ -187,6 +188,29 @@ function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {
return;
}

case ts.SyntaxKind.IfStatement: {
const { expression, thenStatement, elseStatement } = node as ts.IfStatement;
cb(expression, true); // allow truthyness check
cb(thenStatement);
if (elseStatement !== undefined) { cb(elseStatement); }
return;
}

case ts.SyntaxKind.PrefixUnaryExpression: {
const {operator, operand} = node as ts.PrefixUnaryExpression;
cb(operand, operator === ts.SyntaxKind.ExclamationToken); // allow falsyness check
check();
return;
}

case ts.SyntaxKind.ForStatement: {
const { initializer, condition, incrementor, statement } = node as ts.ForStatement;
if (initializer !== undefined) { cb(initializer); }
if (condition !== undefined) { cb(condition, true); } // allow truthyness check
if (incrementor !== undefined) { cb(incrementor); }
return cb(statement);
}

default:
if (!(isExpression(node) && check())) {
return ts.forEachChild(node, cb);
Expand Down Expand Up @@ -230,6 +254,8 @@ function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {
return cb(right);

case ts.SyntaxKind.CommaToken: // Allow `any, any`
case ts.SyntaxKind.BarBarToken: // Allow `any || any`
case ts.SyntaxKind.AmpersandAmpersandToken: // Allow `any && any`
cb(left, /*anyOk*/ true);
return cb(right, /*anyOk*/ true);

Expand Down
5 changes: 5 additions & 0 deletions test/rules/no-unsafe-any/test.ts.lint
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,9 @@ switch (x.y) {

declare global {}

if (x) {}
if (!x) {}
if (!x || x) {}
for (;x;) {}

[0]: Unsafe use of expression of type 'any'.