-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
ref(utils): Use type predicates in is
utility functions
#4124
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
Conversation
size-limit report
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice, good refactor
we can even enforce this with an eslint rule, what do you think? |
What exactly would you test for? |
That maybe it’s not worth the hassle though. |
Ah. Didn't know if you meant that or checking for unnecessary casts. In any case, yeah, I don't think checking the functions themselves is worth it - we add new ones so infrequently, and whoever does the next one will presumably see that all of the others use predicates and will hopefully follow suit. |
This restores part of the work done in #4124, which then got reverted in #4149. The problem there was the predicates for `DOMError` and `DOMException`, both of which only exist in a browser context. This restores the predicates for `isError` and `isString`, which should be safe, because both `Error` and `string` exist in both browser and node contexts.
We have a number of
is
utility functions (isString
,isError
, and so on), and while they tell the human reading the code something about the value in question, they don't tell TypeScript anything, because it doesn't see them as type checks. As a result, we end up with a lot of code like this:where we have to typecast our variables, despite their type already having been checked immediately beforehand.
In order to fix this, TS lets you return a type predicate from a type-checking function rather than a simple boolean, and that lets it know what the human reader knows - if
isString(msg)
is true, thenmsg
must be a string.This switches all of our
is
functions to use type predicates, and removes all of the typecasts which are no longer necessary as a result of this change.