Home > Blockchain >  Why is ESLint complaining about "Unnecessary conditional" when checking if an array value
Why is ESLint complaining about "Unnecessary conditional" when checking if an array value

Time:05-12

const array = [1,2,3]

if (array[5] === undefined)
  array[5] = 5

I'm using Typescript and ESLint and I don't understand why this ESLint error is showing for array[5] === undefined:

Unnecessary conditional, the types have no overlap.ESLint(@typescript-eslint/no-unnecessary-condition)

Since this is an array of numbers ESLint is telling me that the check is an unnecessary conditional. But I want to know if the given index holds a value. What am I supposed to do here instead so the error does not show up?

Here is a Sandbox with the error showing: Sandbox

CodePudding user response:

Because array[5] has the type of number, rather than number | undefined.

In the following example, the error is not present:

const array = [1,2,3]
const item = array[5] as number | undefined

if (item === undefined)
  array[5] = 5

Consider setting "strictNullChecks": true to be able to operate with nulls and undefineds, and setting "noUncheckedIndexedAccess": true to include … | undefined in index signature property access:

{
  "compilerOptions": {
    "strictNullChecks": true,
    "noUncheckedIndexedAccess": true
  }
}
  • Related