"Object is possibly 'null'." despite optional chaining

418 views Asked by At

I am getting Object is possibly 'null'. ts(2531) even though I am using optional chaining and using TypeScript 4.6.3.

const path = fileInput?.files[0]?.path

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"]
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

What am I doing wrong?

1

There are 1 answers

0
Unmitigated On BEST ANSWER

Use optional chaining for the array index access as well.

const path = fileInput?.files?.[0]?.path