Home

GraphProtocol: TS2322 null assignment in Subgraph

The problem statement

You're reading this article because probably you've encountered the following error in Subgraph

ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/Address | null'
is not assignable to type '~lib/@graphprotocol/graph-ts/common/collections/ByteArray'

We have seen this error when trying to assign the transaction.to value to a variable which is not null

if (event.transaction.to) {
  const addr: Address = event.transaction.to; // Error: TS2322
}

As you can see that even thought the assignment is only executed when the to address is not null. The compiler still throws an error.

Solution

This can be solved by explicity specifying that the to address isn't null using non-null assertion operator (exclamation) !

Therefore, the above code can be now written as

if (event.transaction.to) {
  const addr: Address = event.transaction.to!; // This works, note the `!`
}


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments