pmiranda
pmiranda

Reputation: 8470

React and TypeScript, Object is possibly 'null'. TS2531

In React with TypeScript I have this error while building:

Object is possibly 'null'. TS2531

enter image description here

But I have this code:

if (usersNode && usersNode.getLinkedRecords('edges') != null)
usersNode.getLinkedRecords('edges').forEach((edge: any) => {
  const node = edge.getLinkedRecord('node')

  nodesMapping[node.getValue('usuarioId')] = node.getDataID()
})

Why? I'm saying explicitly that if that Object is not null...

Upvotes: 1

Views: 146

Answers (1)

dave
dave

Reputation: 64707

I would imagine that the issue is that

usersNode.getLinkedRecords('edges')

is a function call. Typescript can't "know" that it will return the same thing the second time you call it.

Try

const edges = usersNode && usersNode.getLinkedRecords('edges');
if (edges !== null)
    edges.forEach((edge: any) => {
        const node = edge.getLinkedRecord('node')
        nodesMapping[node.getValue('usuarioId')] = node.getDataID()
    })

Upvotes: 1

Related Questions