Skip to content
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

fix(eslint-plugin): [prefer-optional-chain] properly disambiguate between boolean and false #8685

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
Expand Up @@ -61,17 +61,13 @@ type Operand = ValidOperand | InvalidOperand;
const NULLISH_FLAGS = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
function isValidFalseBooleanCheckType(
node: TSESTree.Node,
operator: TSESTree.LogicalExpression['operator'],
checkType: 'true' | 'false',
disallowFalseyLiteral: boolean,
parserServices: ParserServicesWithTypeInformation,
options: PreferOptionalChainOptions,
): boolean {
const type = parserServices.getTypeAtLocation(node);
const types = unionTypeParts(type);

const disallowFalseyLiteral =
(operator === '||' && checkType === 'false') ||
(operator === '&&' && checkType === 'true');
if (disallowFalseyLiteral) {
/*
```
Expand Down Expand Up @@ -133,6 +129,7 @@ export function gatherLogicalOperands(
const { operands, newlySeenLogicals } = flattenLogicalOperands(node);

for (const operand of operands) {
const areMoreOperands = operand !== operands.at(-1);
switch (operand.type) {
case AST_NODE_TYPES.BinaryExpression: {
// check for "yoda" style logical: null != x
Expand Down Expand Up @@ -258,8 +255,7 @@ export function gatherLogicalOperands(
operand.operator === '!' &&
isValidFalseBooleanCheckType(
operand.argument,
node.operator,
'false',
areMoreOperands && node.operator === '||',
parserServices,
options,
)
Expand All @@ -285,8 +281,7 @@ export function gatherLogicalOperands(
if (
isValidFalseBooleanCheckType(
operand,
node.operator,
'true',
areMoreOperands && node.operator === '&&',
parserServices,
options,
)
Expand Down
Expand Up @@ -1916,6 +1916,25 @@ describe('hand-crafted cases', () => {
},
],
},
{
code: `
declare const foo: { bar: boolean } | null | undefined;
declare function acceptsBoolean(arg: boolean): void;
acceptsBoolean(foo != null && foo.bar);
`,
output: `
declare const foo: { bar: boolean } | null | undefined;
declare function acceptsBoolean(arg: boolean): void;
acceptsBoolean(foo?.bar);
`,
options: [
{
allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing:
true,
},
],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
function foo(globalThis?: { Array: Function }) {
Expand Down