Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat(eslint-plugin): [strict-boolean-expressions] add ignoreRhs option (
  • Loading branch information
Retsam authored and JamesHenry committed Jul 24, 2019
1 parent f6f89e5 commit fd6be42
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 5 deletions.
Expand Up @@ -52,6 +52,12 @@ while (typeof str !== 'undefined') {
}
```

## Options

Options may be provided as an object with:

- `ignoreRhs` to skip the check on the right hand side of expressions like `a && b` or `a || b` - allows these operators to be used for their short-circuiting behavior. (`false` by default).

## Related To

- TSLint: [strict-boolean-expressions](https://palantir.github.io/tslint/rules/strict-boolean-expressions)
33 changes: 28 additions & 5 deletions packages/eslint-plugin/src/rules/strict-boolean-expressions.ts
Expand Up @@ -13,7 +13,13 @@ type ExpressionWithTest =
| TSESTree.IfStatement
| TSESTree.WhileStatement;

export default util.createRule({
type Options = [
{
ignoreRhs?: boolean;
}
];

export default util.createRule<Options, 'strictBooleanExpression'>({
name: 'strict-boolean-expressions',
meta: {
type: 'suggestion',
Expand All @@ -22,13 +28,27 @@ export default util.createRule({
category: 'Best Practices',
recommended: false,
},
schema: [],
schema: [
{
type: 'object',
properties: {
ignoreRhs: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
messages: {
strictBooleanExpression: 'Unexpected non-boolean in conditional.',
},
},
defaultOptions: [],
create(context) {
defaultOptions: [
{
ignoreRhs: false,
},
],
create(context, [{ ignoreRhs }]) {
const service = util.getParserServices(context);
const checker = service.program.getTypeChecker();

Expand Down Expand Up @@ -65,7 +85,10 @@ export default util.createRule({
function assertLocalExpressionContainsBoolean(
node: TSESTree.LogicalExpression,
): void {
if (!isBooleanType(node.left) || !isBooleanType(node.right)) {
if (
!isBooleanType(node.left) ||
(!ignoreRhs && !isBooleanType(node.right))
) {
reportNode(node);
}
}
Expand Down
Expand Up @@ -156,6 +156,15 @@ ruleTester.run('strict-boolean-expressions', rule, {
`
function foo<T extends boolean>(arg: T) { return !arg; }
`,
{
options: [{ ignoreRhs: true }],
code: `
const obj = {};
const bool = false;
const boolOrObj = bool || obj;
const boolAndObj = bool && obj;
`,
},
],

invalid: [
Expand Down Expand Up @@ -903,5 +912,26 @@ ruleTester.run('strict-boolean-expressions', rule, {
},
],
},
{
options: [{ ignoreRhs: true }],
errors: [
{
messageId: 'strictBooleanExpression',
line: 4,
column: 19,
},
{
messageId: 'strictBooleanExpression',
line: 5,
column: 20,
},
],
code: `
const obj = {};
const bool = false;
const objOrBool = obj || bool;
const objAndBool = obj && bool;
`,
},
],
});

0 comments on commit fd6be42

Please sign in to comment.