Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
Description
In v6 we have rewritten theprefer-optional-chain
rule from the ground up.
The new logic assesses the "nullish comparison style" of logical operand in relation to the logical operator to determine if it should be consider part of a chain. EG||
will only assess "equal nullish" checks, and&&
will only assess "not equal to nullish" checks.
This does lead to one hole in the rule:
declareconstfoo:{bar:number}|null;foo===null||foo.bar;foo!==null&&!foo.bar;
In the first casefoo.bar
is seen as a "truthy boolean" check (eg "not equal nullish") - which isn't a valid operand in an "OR" chain.
Similarly in the second case!foo.bar
is seen as a "falsy boolean" check (eg "equal nullish") - which isn't a valid operand in an "AND" chain.
This means that the rule will ignore it and thus will not include it in the chain to report and fix.
This logic is correct and sound - however it doesn't properly encapsulate developer intent. Specifically when that "invalid" chain operand is the very last member in a chain - in certain cases we will actually want to include it as part of the chain.
A slightly longer example:
foo&&foo.bar&&foo.bar.baz===1// rule will currently fix tofoo?.bar&&foo.bar.baz===1// but ideally it would fix it tofoo?.bar?.baz===1
I think there's a subset of checks that it should include:
- "boolean" checks (eg
foo
and!foo
) !==
/===
/!=
/==
comparing against anything excepttypeof
- not
typeof
becausefoo && typeof foo.bar
will returnundefined | typeof foo.bar
whereastypeof foo?.bar
will returntypeof foo.bar | 'undefined'
- which is VERY different
- not
- should not include
>
/>=
/<
/<=
because TS will hard error if one of the operands is nullish.