openimsdk / open-im-sdk-web-wasm

JS SDK for OpenIM Web use by Webassembly of go
https://openim.io
Apache License 2.0
29 stars 37 forks source link

[FEATURE REQUEST] Add type inference for callback functions #86

Closed isaackwok closed 1 month ago

isaackwok commented 1 month ago

Why this feature?

In the current version, we have to define the type of callback function manually:

// ❌ no type
OpenIM.on(CbEvents.OnUserStatusChanged, (event) => {
  // The type of event is WSEvent<any>
  event.data // any
})

// 🤔 manually typed
OpenIM.on(CbEvents.OnUserStatusChanged, (event: WSEvent<UserOnlineState>) => {
  // The type of event is WSEvent<UserOnlineState>
  event.data // UserOnlineState
})

In order to improve developer experience, I suggest adding type inference so that developer can just:

// 🥳 type safe
OpenIM.on(CbEvents.OnUserStatusChanged, (event) => {
  event.data // UserOnlineState
})

Suggested Solution

  1. Define a mapping between CbEvents and the corresponding data.
  2. Add generics to the functions emit(), on() and off() in Emitter class

Additional Information

See pull request #87

No response