I have code that does a regex match, with some optional capturing groups. The code looks something like this:
const match = /some (regex) with (capturing) (groups)/.exec(myInput);
/* eslint-disable-next-line @typescript-eslint/no-unnecessary-condition */
const hideVersion = match[4]?.includes('h');
// ^
My code that looks at the fourth match result, which may or may not exist. I get execution errors if I don't check that match[4]
exists before trying to use it, because it may not be there.
Why is @typscript-eslint
complaining about this check? Is there a way I could rewrite the code such that I'm making the necessary check without making @typescript-eslint
unhappy?
Note: This answer assumes you have noUncheckedIndexedAccess
enabled.
typescript-eslint playground with noUncheckedIndexedAccess
Because TypeScript is lying to you. 🙂
Typed linting, which @typescript-eslint/no-unnecessary-condition
utilizes, directly takes in types from TypeScript to make decisions. If TypeScript thinks match[4]
is defined then the lint rule will too.
TypeScript's type checker by default assumes all array indexes provide a element from the array. match[0]
, match[4]
, and match[9001]
will all be typed as string
, not string | undefined
. This is for the sake of convenience: most of the time, developers prefer assuming array elements will exist.
The opt-in, off-by-default noUncheckedIndexedAccess
TypeScript compiler option switches TypeScript's type checker to be more strict. It changes array index accesses to be typed as the value or undefined
(unless the type is narrowed). This is technically more type-safe but in practice can be very annoying. See https://github.com/microsoft/TypeScript/pull/39560 for more information on why noUncheckedIndexedAccess
isn't enabled by default.
If don't want to enable noUncheckedIndexedAccess
and also really want to avoid using that eslint-disable-next-line
inline config comment to disable the ESLint rule, you can use match.at(4)
instead. But this is one of those rare-but-not-unheard-of cases where a config comment is the right strategy.