How to type async higher-order resolver in Typescript? #2223
-
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? |
Beta Was this translation helpful? Give feedback.
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. |
Beta Was this translation helpful? Give feedback.
-
was getting the same error, changed it to throw the error instead which stopped
|
Beta Was this translation helpful? Give feedback.
-
Hi. We've simplified the annotations for higher-order handlers/resolvers since this question has been posted. Please use the following types: You can find the same types for GraphQL. |
Beta Was this translation helpful? Give feedback.
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.