Skip to content

Support React Native EventEmitter type with fromEvent #3809

@ajcrites

Description

@ajcrites

Feature Request

React Native defines its own EventEmitter type that it claims is a subset of the Node.js EventEmitter type, but it is a bit different: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-native/index.d.ts#L143

Specifically, removeListener returns void. The return type of addListener and parameters are also different, but this doesn't cause a typing problem.

Is your feature request related to a problem? Please describe.
If you attempt to use fromEvent with a React Native EventEmitter implementation such as https://github.com/urbanairship/react-native-module you will get a type error:

fromEvent(UrbanAirship, 'pushReceived');

Argument of type 'typeof UrbanAirship' is not assignable to parameter of type 'FromEventTarget<{}>'.
  Type 'typeof UrbanAirship' is not assignable to type 'ArrayLike<EventTargetLike<{}>>'.
    Index signature is missing in type 'typeof UrbanAirship'.

Describe the solution you'd like
There are at least two solutions:

  1. Add a ReactNativeEventEmitter type.
  2. Allow addListener and removeListener for NodeStyleEventEmitter to return any.

The isNodeStyleEventEmitter check can be used for both, but unfortunately I don't think there is a way to know whether the provided EventEmitter is Node.js style or React Native except based on type. However, the return types for addListener and removeListener are not used, so being able to distinguish between them at runtime won't matter at this time.

Describe alternatives you've considered
You can of course do fromEvent(UrbanAirship as any... or use fromEventPattern, but these are more verbose and you lose type safety you could get from the former.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurePRs and issues for features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions