Next.js Discord

Discord Forum

Help with TypeScript and server actions

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
I wanted to abstract the way my server actions return error responses by creating a helper function that checks for error type, and returns the appropriate response. But this has backfired since I have lost type-safety which I had previously.

My server actions look something like this:

export async function getUser(userId: string) {
  try {
    // throws AuthorizationError if user is not admin
    await authorize((user) => user.role === "admin");
    const user = await getUserFromDb(userId);

    if (!user) throw new NotFoundError("User not found");

    return {
      ok: true,
      status: 200,
      data: users
    }
  } catch (error) {
    return responseError(error);
  }
}


Before introducing the responseError function the TypeScript knew that the only way data is available is if ok was true, and that error is available if ok was false.

What's annoying is that if I copy the contents of my responseError function and just paste it in my catch block the typescript is fixed. Do you guys have ideas on how I can go about fixing this, without manually typing every server action function return value?

// abstraction of errors
export type ErrorResponseType = {
  ok: false;
  status: 400 | 401 | 404 | 500;
  error: Error | ZodError | NotFoundError | UserInputError | AuthorizationError;
};

export function responseError(error: unknown): ErrorResponseType
  if (error instanceof AuthorizationError) {
    return {
      ok: false,
      status: 401,
      error: error,
    };
  if (error instanceof ZodError)
    return {
      ok: false,
      status: 400,
      error: error,
    };
  // ...

0 Replies