-
-
Notifications
You must be signed in to change notification settings - Fork 366
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 JSON generics to ky() and HTTPError #619
Conversation
Relates to sindresorhus#312 All of the following forms are supported: - `ky<T>()` - `ky.get<T>()` (all methods) - `ky().json<T>()` - `(await ky()).json<T>()`
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.
Looks good! Thanks for your efforts on getting this done 😄
This is neat. What do you think of adding a second generic type parameter for the expected Error payload too? try {
// user is a User
const user = await ky<User, UserGetError>('/api/users/2').json();
} catch (exception) {
if (exception instanceof HTTPError) {
// error is UserGetError
const error = await exception.response.json();
}
} |
Seems like a good idea. 👍 |
Oh, it might already be there, kind of. Plus, I don't think there's a way in TypeScript to propagate a generic type parameter from a method call through to an exception that is thrown and it show up in the I think this works as is though: try {
// user is a User
const user = await ky<User>("/api/users/2").json();
} catch (exception) {
if (exception instanceof HTTPError) {
// exception is UserGetError
const error = await exception.response.json<UserGetError>();
}
} In fact, I see that |
I suppose when creating instances manually it is. |
It was added because of #615. See that issue for how and why you might use the generic for And if TypeScript ever does allow functions to type their exceptions, |
Closes #615
Closes #485
Relates to #312
This PR adds support for an optional TypeScript generic type parameter in all request methods, passes it through the request, response promise, and response, and into
.json()
, so that users have more flexibility in where and how they type their JSON objects.All of the following forms are supported:
ky<T>()
ky.get<T>()
(all methods)ky().json<T>()
(await ky()).json<T>()
The
HTTPError
class has similarly been updated and passes its type parameter through toerror.response.json()
. See #615 for an example of how this could be used.