I am trying to retrieve data from a mock api call using msw while using Typescript. How would I go about doing this? I keep receiving "Property 'email' does not exist on type 'DefaultBodyType'"
Handler
export const handlers: RestHandler[] = [
rest.post(`/${API_VERSION}/authentication/login`, (req, res, ctx) => {
const {email} = req.body;
console.log();
return res(
ctx.status(200),
ctx.json({
token: "abdb23231232jdsaWEDwdxaCDA",
expiresIn: 100000,
isEnabled: true,
isLocked: false,
})
);
})
];
You need to give the handler itself some types, describing what the request body and response body should look like.
interface LoginRequestBody {
email: string;
}
interface LoginResponseBody {
token: string,
expiresIn: number;
isEnabled: boolean;
isLocked: boolean,
}
export const handlers = [
rest.post<LoginRequestBody, LoginResponseBody>(`/${API_VERSION}/authentication/login`, (req, res, ctx) => {
const {email} = req.body;
console.log();
return res(
ctx.status(200),
ctx.json({
token: "abdb23231232jdsaWEDwdxaCDA",
expiresIn: 100000,
isEnabled: true,
isLocked: false,
})
);
})
];
You also don't need RestHandler[]
as it's inferred.
This article written by the MSW maintainer may help understand more about types as well.