Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Error Types #10

Closed
wants to merge 1 commit into from

Conversation

seveibar
Copy link

@seveibar seveibar commented Jan 29, 2023

I like this module a lot! I think it would be even better if we were able to define possible resulting errors. I've adding backwards-compatible types for errors here, people might use this when they have known errors being returned by a function.

At seam.co we have really error-heavy code, so we usually have types for all the errors that could be returned by a function. This might be one step towards getting all those errors nicely typed.

Example code BEFORE ErrorType introduced:

  const result = await pReflect(
    getFromGithub("/users/thispersondoesnotexist99829384", {})
  )
  if (isRejected(result)) {
    result.reason // type: unknown
  }

Example code after:

const result = await pReflect<APIResponse, NotFoundError>(
  getFromGithub("/users/thispersondoesnotexist99829384", {})
)

if (isRejected(result)) {
  result.reason // type: NotFoundError
}

I'm interested in comments but I think due to Typescript's all-or-nothing generics this feature might not be very helpful. (see how I have to include APIResponse in the AFTER type above?)

@seveibar seveibar changed the title Add support for error types Add support for Error Types Jan 29, 2023
@seveibar seveibar marked this pull request as ready for review January 29, 2023 20:27
@seveibar seveibar marked this pull request as draft January 29, 2023 20:47
@seveibar
Copy link
Author

seveibar commented Jan 29, 2023

Not entirely satisfied with this, converting back to draft.

I've edited the original post to include some reasoning why the interface sort of has to be ugly and require redundant specification of the value type.

@sindresorhus
Copy link
Owner

I cannot think of a better way either. I think it's fine though. If you really want strongly-typed errors, you need some more boilerplate for now, if not, you don't specify any type parameter. We can add a TODO comment about using type placeholder when it eventually becomes a reality.

@sindresorhus
Copy link
Owner

Bump :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants