Devator
Devator

Reputation: 3904

Typescript TS2532: Object is possibly 'undefined' even though I'm actually checking

I have this weird issue where I don't understand why Typescript keeps complaining about a possible undefined value:

Webstorm error

if (!flatListRef || !flatListRef.current) return

flatListRef.current.someMethod()

This code returns the same error:

if (flatListRef && flatListRef.current) {
    flatListRef.current.someMethod()
}

So does this piece of code:

flatListRef?.current?.someMethod()

And also this:

flatListRef!.current!.someMethod()

I'm running Typescript 4.3.5 targetting es6 and have no idea why TS2532 keeps popping. I've tried upgrading all my packages but I have no clue on how to debug this issue. Any hints would be greatly appreciated :-).

My tsconfig.json:

{
  "compilerOptions": {
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "jsx": "react-native",
    "esModuleInterop": true,
    "module": "es2015",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "sourceMap": true,
    "target": "es6",
    "lib": [
      "esnext",
      "dom"
    ],
    "skipLibCheck": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "App.js",
    "app",
    "test",
    "storybook"
  ]
}

Upvotes: 1

Views: 1004

Answers (1)

Nikita Ivanov
Nikita Ivanov

Reputation: 856

(from a comment above)

strictNullChecks flag should be enabled. If it's not, I suppose that tsc ignores all typeguards that are used to check that a variable is not null (and undefined)

Upvotes: 1

Related Questions