react-native-branch-deep-linking-attribution icon indicating copy to clipboard operation
react-native-branch-deep-linking-attribution copied to clipboard

Add export to error and success event type

Open vincent-paing opened this issue 2 years ago • 0 comments

Added export for success and error event to write type guard easily.

With current implementation we have to either do a force non-null or a null check on params regardless of whether you null check error or not.

branch.subscribe(({error, params}) => {
  if (error) {
    console.log(error);
  } else {
    // params could still be undefined here, thus require force non-null, otherwise lint complain
    doSomethingWithParams(params);
  }
});

A better solution is to to write a typeguard like below:

function isErrorEvent(
  event: BranchSubscriptionEvent,
): event is BranchSubscriptionEventError {
  return typeof event.error === 'string';
}

branch.subscribe((event: BranchSubscriptionEvent) => {
  if (isErrorEvent(event)) {
    console.log(event.error);
  } else {
    // param cannot be undefined, no additional check needed
    doSomethingWithParams(event.params);
  }
});

However, to write this type guard, you need to copy paste the type definition of BranchSubscriptionEventError and BranchSubscriptionEventBase since it is not exported from the library. The PR is to address this and make it easier for user to integrate a proper type guard in their code without having to copy paste from library. Note that copy-pasting could also lead to potential error in future when the library updates their type, so I'd prefer to use the one existing in the library. Ideally, it would be even better if the isErrorEvent typeguard is written and exported from the library itself, but I'm not sure where to put this code. I'm more than happy to update the PR with the typeguard function if you give me a direction on where to put it.

I made a repo for you so that you can check out what I meant and play around with it

vincent-paing avatar Mar 26 '22 07:03 vincent-paing