Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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;
`,
},
],
});