TypeChain icon indicating copy to clipboard operation
TypeChain copied to clipboard

Incorrect return type for web3-v1 events

Open olehmisar opened this issue 4 years ago • 3 comments

web3.eth.Contract().events.SomeEvent(callback) returns Subscription object but the generated return type is EventEmitter.

typechain --target=web3-v1 generates this:

export interface MyContract extends BaseContract {
  events: {
    SomeEvent(cb?: Callback<SomeEvent>): EventEmitter;
  }
}

...but should generate this:

export interface MyContract extends BaseContract {
  events: {
    SomeEvent(cb?: Callback<SomeEvent>): Subscription;  // <--- different return type
  }
}

olehmisar avatar Jun 12 '21 13:06 olehmisar

Looks like Subscription is inheriting from EventEmitter. So the generated return type is correct but it doesn't allow me to write react code like this:

useEffect(() => {
  const subscription = myContract.events.SomeEvent(callback)
  return () => {
    subscription.unsubscribe() // ERROR: Property 'unsubscribe' does not exist on type 'EventEmitter'.
  }
})

olehmisar avatar Jun 12 '21 14:06 olehmisar

After looking into the web3.js documentation, I found out that it is documented that myContract.events.SomeEvent returns EventEmitter. Looks like it is incorrectly documented because if you actually console.log(subscription) it shows that the returned value is of type Subscription. image

olehmisar avatar Jun 12 '21 14:06 olehmisar

Thanks for investigating it. I would suggest making web3js team aware of the documentation issue.

As for TypeChain related fix, I am all for improving it on our side as well. I personally don't use web3 so your best chance would be to fix it by yourself by creating a PR.

Let me know if you need help!

krzkaczor avatar Jun 14 '21 07:06 krzkaczor