DEV Community

Discussion on: Type-safe API mocking with Mock Service Worker and TypeScript

Collapse
 
wati_fe profile image
Boluwatife Fakorede

Hello Artem, great article, and thank you.

I do have a question, how do you define the response body interface if you want to return either an error response or a true response. Example below:

  rest.get<TodoId>(`${apiUrl}/todo`, async (req, res, ctx) => {
    const {todoId} = req.body
    const todo = await todosDB.read(todoId)
    if (!todo) {
      return res(
        ctx.status(404),
        ctx.json({status: 404, message: 'Todo not found'}),
      )
    }

    return res(ctx.json({todo}))
  }),
Enter fullscreen mode Exit fullscreen mode

Thank you very much

Collapse
 
kettanaito profile image
Artem Zakharchenko

Thank you, Fakorede.

With the current implementation you'd have to use a union type to define such response:

interface TodoResponsePayload {
  todo: Todo
}

interface TodoResponseError {
  status: number
  message: string
}

type TodoResponse = TodoResponsePayload | TodoResponseError

rest.get<TodoId, TodoResponse>('/todo', handler).
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wati_fe profile image
Boluwatife Fakorede

Great. Thanks for your response