-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(eslint-plugin): add rule strict-boolean-expressions #579
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bradzacher
merged 7 commits into
typescript-eslint:master
from
jonathanrdelgado:strict-boolean-expressions
Jul 1, 2019
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f9cc27c
feat(eslint-plugin): strict-boolean-expressions
jonathanrdelgado f6d869b
chore(eslint-plugin): fix readme build
jonathanrdelgado 43ba5be
chore(eslint-plugin): improve coverage
jonathanrdelgado 724ae70
Merge branch 'master' into strict-boolean-expressions
bradzacher 7461986
Merge branch 'master' into strict-boolean-expressions
bradzacher f3b7161
chore(eslint-plugin): refactor
jonathanrdelgado 6ea5732
Merge branch 'master' into strict-boolean-expressions
bradzacher File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 57 additions & 0 deletions
57
packages/eslint-plugin/docs/rules/strict-boolean-expressions.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
# Boolean expressions are limited to booleans (strict-boolean-expressions) | ||
|
||
Requires that any boolean expression is limited to true booleans rather than | ||
casting another primitive to a boolean at runtime. | ||
|
||
It is useful to be explicit, for example, if you were trying to check if a | ||
number was defined. Doing `if (number)` would evaluate to `false` if `number` | ||
was defined and `0`. This rule forces these expressions to be explicit and to | ||
strictly use booleans. | ||
|
||
The following nodes are checked: | ||
|
||
- Arguments to the `!`, `&&`, and `||` operators | ||
- The condition in a conditional expression `(cond ? x : y)` | ||
- Conditions for `if`, `for`, `while`, and `do-while` statements. | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```ts | ||
const number = 0; | ||
if (number) { | ||
return; | ||
} | ||
|
||
let foo = bar || 'foobar'; | ||
|
||
let undefinedItem; | ||
let foo = undefinedItem ? 'foo' : 'bar'; | ||
|
||
let str = 'foo'; | ||
while (str) { | ||
break; | ||
} | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```ts | ||
const number = 0; | ||
if (typeof number !== 'undefined') { | ||
return; | ||
} | ||
|
||
let foo = typeof bar !== 'undefined' ? bar : 'foobar'; | ||
|
||
let undefinedItem; | ||
let foo = typeof undefinedItem !== 'undefined' ? 'foo' : 'bar'; | ||
|
||
let str = 'foo'; | ||
while (typeof str !== 'undefined') { | ||
break; | ||
} | ||
``` | ||
|
||
## Related To | ||
|
||
- TSLint: [strict-boolean-expressions](https://palantir.github.io/tslint/rules/strict-boolean-expressions) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
101 changes: 101 additions & 0 deletions
101
packages/eslint-plugin/src/rules/strict-boolean-expressions.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import { | ||
TSESTree, | ||
AST_NODE_TYPES, | ||
} from '@typescript-eslint/experimental-utils'; | ||
import ts from 'typescript'; | ||
import * as tsutils from 'tsutils'; | ||
import * as util from '../util'; | ||
|
||
type ExpressionWithTest = | ||
| TSESTree.ConditionalExpression | ||
| TSESTree.DoWhileStatement | ||
| TSESTree.ForStatement | ||
| TSESTree.IfStatement | ||
| TSESTree.WhileStatement; | ||
|
||
export default util.createRule({ | ||
name: 'strict-boolean-expressions', | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: 'Restricts the types allowed in boolean expressions', | ||
category: 'Best Practices', | ||
recommended: false, | ||
}, | ||
schema: [], | ||
messages: { | ||
strictBooleanExpression: 'Unexpected non-boolean in conditional.', | ||
}, | ||
}, | ||
defaultOptions: [], | ||
create(context) { | ||
const service = util.getParserServices(context); | ||
const checker = service.program.getTypeChecker(); | ||
|
||
/** | ||
* Determines if the node has a boolean type. | ||
*/ | ||
function isBooleanType(node: TSESTree.Node): boolean { | ||
const tsNode = service.esTreeNodeToTSNodeMap.get<ts.ExpressionStatement>( | ||
node, | ||
); | ||
const type = util.getConstrainedTypeAtLocation(checker, tsNode); | ||
return tsutils.isTypeFlagSet(type, ts.TypeFlags.BooleanLike); | ||
} | ||
|
||
/** | ||
* Asserts that a testable expression contains a boolean, reports otherwise. | ||
* Filters all LogicalExpressions to prevent some duplicate reports. | ||
*/ | ||
function assertTestExpressionContainsBoolean( | ||
node: ExpressionWithTest, | ||
): void { | ||
if ( | ||
node.test !== null && | ||
node.test.type !== AST_NODE_TYPES.LogicalExpression && | ||
!isBooleanType(node.test) | ||
) { | ||
reportNode(node.test); | ||
} | ||
} | ||
|
||
/** | ||
* Asserts that a logical expression contains a boolean, reports otherwise. | ||
*/ | ||
function assertLocalExpressionContainsBoolean( | ||
node: TSESTree.LogicalExpression, | ||
): void { | ||
if (!isBooleanType(node.left) || !isBooleanType(node.right)) { | ||
reportNode(node); | ||
} | ||
} | ||
j-f1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Asserts that a unary expression contains a boolean, reports otherwise. | ||
*/ | ||
function assertUnaryExpressionContainsBoolean( | ||
node: TSESTree.UnaryExpression, | ||
): void { | ||
if (!isBooleanType(node.argument)) { | ||
reportNode(node.argument); | ||
} | ||
} | ||
|
||
/** | ||
* Reports an offending node in context. | ||
*/ | ||
function reportNode(node: TSESTree.Node): void { | ||
context.report({ node, messageId: 'strictBooleanExpression' }); | ||
} | ||
|
||
return { | ||
ConditionalExpression: assertTestExpressionContainsBoolean, | ||
DoWhileStatement: assertTestExpressionContainsBoolean, | ||
ForStatement: assertTestExpressionContainsBoolean, | ||
IfStatement: assertTestExpressionContainsBoolean, | ||
WhileStatement: assertTestExpressionContainsBoolean, | ||
LogicalExpression: assertLocalExpressionContainsBoolean, | ||
'UnaryExpression[operator="!"]': assertUnaryExpressionContainsBoolean, | ||
}; | ||
}, | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.