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 all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/rules/noUnsafeAnyRule.ts
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
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'.