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 isErrorObject type guard / function #47

Closed
fregante opened this issue Jun 16, 2021 · 5 comments · Fixed by #68
Closed

Add isErrorObject type guard / function #47

fregante opened this issue Jun 16, 2021 · 5 comments · Fixed by #68

Comments

@fregante
Copy link
Contributor

What do you think about exporting a type-checker function (like Array.isArray) that doubles as a type guard?

export function isErrorObject(error: unknown): error is ErrorObject {
  return error && typeof error === 'object' && 'message' in error;
}
@sindresorhus
Copy link
Owner

What would you use it for that is related to this package?

@fregante
Copy link
Contributor Author

To detect whether is a serialized error or regular error. Example:

try {

} catch(error: unknown) {
  if (isErrorObject(error) && error.message === blah) {
    // ignore
  } else {
    throw error
  }
}

Typescript makes it a pain to check properties of unknown objects, even with ?., so a type guard would make it easier

@sindresorhus
Copy link
Owner

Yes, but why have it here and not in https://github.com/sindresorhus/is? And what properties should it enforce?

I think it should be named isErrorLike. This is consistent with TypeScript methods for duck-typing, like the PromiseLike type.

https://stackoverflow.com/questions/43712705/why-does-typescript-use-like-types

@fregante
Copy link
Contributor Author

fregante commented Jun 17, 2021

Here because {message: string} isn’t really an error on its own, but this package can turn it into one. I don’t think it would make sense in is

isErrorLike could also work but isErrorObject matches the name you’re using here.

In this package the type ErrorObject could also make a little more tight because currently it matches {}, but that’s another issue.

@sindresorhus
Copy link
Owner

sindresorhus commented Jun 17, 2021

Ah, I see. Ok, sure, let's add. isErrorObject is fine.

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

Successfully merging a pull request may close this issue.

2 participants