How to type async higher-order resolver in Typescript? #2223
Answered
by
kettanaito
Lee-Minhoon
asked this question in
Q&A
|
I referred to the "https://mswjs.io/docs/best-practices/typescript/#higher-order-response-resolvers page and wrote the code as follows. import {
DefaultBodyType,
HttpResponse,
HttpResponseResolver,
PathParams,
} from "msw";
type HigherOrderResolver = <
Params extends PathParams,
RequestBodyType extends DefaultBodyType,
ResponseBodyType extends DefaultBodyType ,
>(
resolver: HttpResponseResolver<Params, RequestBodyType, ResponseBodyType>
) => HttpResponseResolver<Params, RequestBodyType, ResponseBodyType>;
export const withAuth: HigherOrderResolver = (resolver) => {
return (input) => {
const { request } = input;
if (!request.headers.get("Authorization")) {
return HttpResponse.json(
{ data: null, message: "Unauthorized" },
{ status: 401 }
);
}
return resolver(input);
};
};However, a TypeScript error appears where the response is returned. This is probably due to the application of the 'NoInfer' type. Injecting the exact type into the generic makes it difficult to write a general-purpose type. Is there a good way to solve this? |
Answered by
kettanaito
Nov 27, 2024
Replies: 3 comments
|
I'd also be interested to know if there's a good solution for this. I'm trying to replicate the auth example given for plain JavaScript but with TypeScript. |
0 replies
|
was getting the same error, changed it to throw the error instead which stopped |
0 replies
Answer selected by
kettanaito
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. We've simplified the annotations for higher-order handlers/resolvers since this question has been posted. Please use the following types:
HttpHandler:msw/src/core/index.ts
Line 8 in 3cc9d9f
HttpResponseResolver:msw/src/core/index.ts
Line 46 in 3cc9d9f
You can find the same types for GraphQL.