Infer resolver's response body type from return type of given fetcher function #1171
-
Hey! I would like to keep in sync what my fetcher functions return and what I return from my resolvers (as response body). So when the type of the fetcher function changes, the MSW resolvers will remember you to also change that response body (via a TypeScript error 😅). Maybe I missed something in the docs, but as far as I can tell, when defining resolvers, their response body cannot be inferred out of the box (with MSW I thought about using the return type of my real fetcher function to specify the resolver's generic for the response body. // fetcher function
export async function fetchMyData(): Promise<MyData> {
...
}
// helper type for the response result
type ResponseResult<TFunction extends (...args: any[]) => Promise<unknown>> =
Awaited<ReturnType<TFunction>>;
// handlers
export const handlers = [
// use the response result here for the generic
rest.get<null, any, ResponseResult<typeof fetchMyData>>(
`${apiPrefix}/my-data`,
(req, res, ctx) => {
// `ctx.json` is now type-safe (inferred to `MyData` from `fetchMyData`)
return res(ctx.json({
a: 123
}));
}
),
]; A few questions:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hey, @bennettdams. Thanks for raising this. I believe you can achieve what you want simply by providing the interface MyData {
username: string
}
function fetcher(): Promise<MyData> {}
rest.post<never, MyData>('/resource', (req, res, ctx) => {
return res(ctx.json({ username: 'octocat' }))
}) Also note that the generic signature is Lines 12 to 16 in c30bcd5 The third generic |
Beta Was this translation helpful? Give feedback.
Hey, @bennettdams. Thanks for raising this.
I believe you can achieve what you want simply by providing the
MyData
type as theResponseBodyType
generic to REST API request handlers:Also note that the generic signature is
RequestBodyType, ResponseBodyType
:msw/src/rest.ts
Lines 12 to 16 in c30bcd5
The thir…