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

Commit

Permalink
no-unsafe-any: allow truthyness and falsyness checks (#3008)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajafff authored and adidahiya committed Jul 7, 2017
1 parent 8de7cae commit 37966e9
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
31 changes: 31 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,34 @@ 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);
}

case ts.SyntaxKind.DoStatement:
case ts.SyntaxKind.WhileStatement:
cb((node as ts.IterationStatement).statement);
return cb((node as ts.DoStatement | ts.WhileStatement).expression, true);

default:
if (!(isExpression(node) && check())) {
return ts.forEachChild(node, cb);
Expand Down Expand Up @@ -230,6 +259,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
7 changes: 7 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,11 @@ switch (x.y) {

declare global {}

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

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

0 comments on commit 37966e9

Please sign in to comment.