-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(eslint-plugin): add no-unnecessary-condition rule #699
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
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
5ec23e1
feat(eslint-plugin): [no-unnecessary-condition] add rule
Retsam 0719da8
docs(eslint-plugin): document as related to strict-boolean-expressions
Retsam 9cbe4d8
test(eslint-plugin): add tests for generic type params
Retsam c2a8217
chore(eslint-plugin): fix new lint errors
Retsam 2d6e759
chore(eslint-plugin): add requiresTypeChecking
Retsam 36d5f5c
chore(eslint-plugin): add more comments to example code
Retsam 5df4788
test(eslint-plugin): additional cases for generic params
Retsam be3dd52
feat(estlint-plugin): check BooleanExpressions in no-constant-condition
Retsam 5183fb6
Fixes from code review
Retsam e43ed9b
Merge branch 'master' into allow-truthy
bradzacher 17f0e25
fix formatting
bradzacher d55a6f4
Merge branch 'master' into allow-truthy
bradzacher 20958a2
Merge branch 'master' into allow-truthy
JamesHenry 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
64 changes: 64 additions & 0 deletions
64
packages/eslint-plugin/docs/rules/no-unnecessary-condition.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,64 @@ | ||
# Condition expressions must be necessary | ||
|
||
Any expression being used as a condition must be able to evaluate as truthy or falsy in order to be considered "necessary". Conversely, any expression that always evaluates to truthy or always evaluates to falsy, as determined by the type of the expression, is considered unnecessary and will be flagged by this rule. | ||
|
||
The following expressions are checked: | ||
|
||
- Arguments to the `&&`, `||` and `?:` (ternary) operators | ||
- Conditions for `if`, `for`, `while`, and `do-while` statements. | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```ts | ||
function head<T>(items: T[]) { | ||
// items can never be nullable, so this is unnecessary | ||
if (items) { | ||
Retsam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return items[0].toUpperCase(); | ||
} | ||
} | ||
|
||
function foo(arg: 'bar' | 'baz') { | ||
// arg is never nullable or empty string, so this is unnecessary | ||
if (arg) { | ||
} | ||
} | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```ts | ||
function head<T>(items: T[]) { | ||
// Necessary, since items.length might be 0 | ||
if (items.length) { | ||
return items[0].toUpperCase(); | ||
} | ||
} | ||
|
||
function foo(arg: string) { | ||
// Necessary, since foo might be ''. | ||
if (arg) { | ||
} | ||
} | ||
``` | ||
|
||
## Options | ||
|
||
Accepts an object with the following options: | ||
|
||
- `ignoreRhs` (default `false`) - doesn't check if the right-hand side of `&&` and `||` is a necessary condition. For example, the following code is valid with this option on: | ||
|
||
```ts | ||
function head<T>(items: T[]) { | ||
return items.length && items[0].toUpperCase(); | ||
} | ||
``` | ||
|
||
## When Not To Use It | ||
|
||
The main downside to using this rule is the need for type information. | ||
|
||
## Related To | ||
|
||
- ESLint: [no-constant-condition](https://eslint.org/docs/rules/no-constant-condition) - this rule is essentially a stronger versison | ||
|
||
- [strict-boolean-expression](./strict-boolean-expressions.md) - a stricter alternative to this rule. |
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
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
192 changes: 192 additions & 0 deletions
192
packages/eslint-plugin/src/rules/no-unnecessary-condition.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,192 @@ | ||
import { | ||
TSESTree, | ||
AST_NODE_TYPES, | ||
} from '@typescript-eslint/experimental-utils'; | ||
import ts, { TypeFlags } from 'typescript'; | ||
import { | ||
isTypeFlagSet, | ||
unionTypeParts, | ||
isFalsyType, | ||
isBooleanLiteralType, | ||
isLiteralType, | ||
} from 'tsutils'; | ||
import { | ||
createRule, | ||
getParserServices, | ||
getConstrainedTypeAtLocation, | ||
} from '../util'; | ||
|
||
// Truthiness utilities | ||
// #region | ||
const isTruthyLiteral = (type: ts.Type): boolean => | ||
isBooleanLiteralType(type, true) || (isLiteralType(type) && !!type.value); | ||
|
||
const isPossiblyFalsy = (type: ts.Type): boolean => | ||
unionTypeParts(type) | ||
// PossiblyFalsy flag includes literal values, so exclude ones that | ||
// are definitely truthy | ||
.filter(t => !isTruthyLiteral(t)) | ||
.some(type => isTypeFlagSet(type, ts.TypeFlags.PossiblyFalsy)); | ||
|
||
const isPossiblyTruthy = (type: ts.Type): boolean => | ||
unionTypeParts(type).some(type => !isFalsyType(type)); | ||
|
||
// isLiteralType only covers numbers and strings, this is a more exhaustive check. | ||
const isLiteral = (type: ts.Type): boolean => | ||
isBooleanLiteralType(type, true) || | ||
isBooleanLiteralType(type, false) || | ||
type.flags === ts.TypeFlags.Undefined || | ||
type.flags === ts.TypeFlags.Null || | ||
type.flags === ts.TypeFlags.Void || | ||
isLiteralType(type); | ||
// #endregion | ||
|
||
type ExpressionWithTest = | ||
| TSESTree.ConditionalExpression | ||
| TSESTree.DoWhileStatement | ||
| TSESTree.ForStatement | ||
| TSESTree.IfStatement | ||
| TSESTree.WhileStatement; | ||
|
||
export type Options = [ | ||
{ | ||
ignoreRhs?: boolean; | ||
}, | ||
]; | ||
|
||
export type MessageId = | ||
| 'alwaysTruthy' | ||
| 'alwaysFalsy' | ||
| 'literalBooleanExpression' | ||
| 'never'; | ||
export default createRule<Options, MessageId>({ | ||
name: 'no-unnecessary-conditionals', | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: | ||
'Prevents conditionals where the type is always truthy or always falsy', | ||
category: 'Best Practices', | ||
recommended: false, | ||
requiresTypeChecking: true, | ||
}, | ||
schema: [ | ||
{ | ||
type: 'object', | ||
properties: { | ||
ignoreRhs: { | ||
type: 'boolean', | ||
}, | ||
}, | ||
additionalProperties: false, | ||
}, | ||
], | ||
messages: { | ||
alwaysTruthy: 'Unnecessary conditional, value is always truthy.', | ||
alwaysFalsy: 'Unnecessary conditional, value is always falsy.', | ||
literalBooleanExpression: | ||
'Unnecessary conditional, both sides of the expression are literal values', | ||
never: 'Unnecessary conditional, value is `never`', | ||
}, | ||
}, | ||
defaultOptions: [ | ||
{ | ||
ignoreRhs: false, | ||
}, | ||
], | ||
create(context, [{ ignoreRhs }]) { | ||
const service = getParserServices(context); | ||
const checker = service.program.getTypeChecker(); | ||
|
||
function getNodeType(node: TSESTree.Node): ts.Type { | ||
const tsNode = service.esTreeNodeToTSNodeMap.get(node); | ||
return getConstrainedTypeAtLocation(checker, tsNode); | ||
} | ||
|
||
/** | ||
* Checks if a conditional node is necessary: | ||
* if the type of the node is always true or always false, it's not necessary. | ||
*/ | ||
function checkNode(node: TSESTree.Node): void { | ||
const type = getNodeType(node); | ||
|
||
// Conditional is always necessary if it involves `any` or `unknown` | ||
if (isTypeFlagSet(type, TypeFlags.Any | TypeFlags.Unknown)) { | ||
bradzacher marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return; | ||
} | ||
if (isTypeFlagSet(type, TypeFlags.Never)) { | ||
context.report({ node, messageId: 'never' }); | ||
} else if (!isPossiblyTruthy(type)) { | ||
context.report({ node, messageId: 'alwaysFalsy' }); | ||
} else if (!isPossiblyFalsy(type)) { | ||
context.report({ node, messageId: 'alwaysTruthy' }); | ||
} | ||
} | ||
|
||
/** | ||
* Checks that a binary expression is necessarily conditional, reports otherwise. | ||
* If both sides of the binary expression are literal values, it's not a necessary condition. | ||
* | ||
* NOTE: It's also unnecessary if the types that don't overlap at all | ||
* but that case is handled by the Typescript compiler itself. | ||
*/ | ||
const BOOL_OPERATORS = new Set([ | ||
'<', | ||
'>', | ||
'<=', | ||
'>=', | ||
'==', | ||
'===', | ||
'!=', | ||
'!==', | ||
]); | ||
function checkIfBinaryExpressionIsNecessaryConditional( | ||
node: TSESTree.BinaryExpression, | ||
): void { | ||
if ( | ||
BOOL_OPERATORS.has(node.operator) && | ||
isLiteral(getNodeType(node.left)) && | ||
isLiteral(getNodeType(node.right)) | ||
) { | ||
context.report({ node, messageId: 'literalBooleanExpression' }); | ||
} | ||
} | ||
|
||
/** | ||
* Checks that a testable expression is necessarily conditional, reports otherwise. | ||
* Filters all LogicalExpressions to prevent some duplicate reports. | ||
*/ | ||
function checkIfTestExpressionIsNecessaryConditional( | ||
node: ExpressionWithTest, | ||
): void { | ||
if ( | ||
node.test !== null && | ||
node.test.type !== AST_NODE_TYPES.LogicalExpression | ||
) { | ||
checkNode(node.test); | ||
} | ||
} | ||
|
||
/** | ||
* Checks that a logical expression contains a boolean, reports otherwise. | ||
*/ | ||
function checkLogicalExpressionForUnnecessaryConditionals( | ||
node: TSESTree.LogicalExpression, | ||
): void { | ||
checkNode(node.left); | ||
if (!ignoreRhs) { | ||
checkNode(node.right); | ||
} | ||
} | ||
|
||
return { | ||
BinaryExpression: checkIfBinaryExpressionIsNecessaryConditional, | ||
ConditionalExpression: checkIfTestExpressionIsNecessaryConditional, | ||
DoWhileStatement: checkIfTestExpressionIsNecessaryConditional, | ||
ForStatement: checkIfTestExpressionIsNecessaryConditional, | ||
IfStatement: checkIfTestExpressionIsNecessaryConditional, | ||
WhileStatement: checkIfTestExpressionIsNecessaryConditional, | ||
LogicalExpression: checkLogicalExpressionForUnnecessaryConditionals, | ||
}; | ||
}, | ||
}); |
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.