pwuexecP
Convex Community13mo ago
5 replies
pwuexec

How can I avoid explicitly defining type in TypeScript for a internal call query handler?

I'm loving Convex <3, and I'd like to simplify my code. I have a query handler where I define a specific response type, but I want TypeScript to automatically infer the return type, instead of explicitly specifying something like GetMeResponse | null.

Here’s an example of my current implementation:

type GetMeResponse = {
  _id: Id<"users">;
  name: string;
  email: string;
  role: string;
  isTutor: boolean;
  isStudent: boolean;
  stripeCustomerId?: string;
  imageUrl?: string;
};

export const getMe = query({
  handler: async (ctx): Promise<GetMeResponse | null> => {
    const userId = await getAuthUserId(ctx);
    if (!userId) return null;

    const user = await ctx.db.get(userId);

    if (!user) {
      throw new Error("User not found");
    }

    if (!user.name) {
      throw new Error("User name not found");
    }

    if (!user.email) {
      throw new Error("User email not found");
    }

    if (!user.role) {
      throw new Error("User role not found");
    }

    return {
      _id: userId,
      name: user.name,
      email: user.email,
      role: user.role,
      isTutor: user.role === ROLES.TUTOR,
      isStudent: user.role === ROLES.STUDENT,
      stripeCustomerId: user.stripeCustomerId,
      imageUrl: user.image,
    };
  },
});

export const getMeOrThrow = query({
  handler: async (ctx): Promise<GetMeResponse> => {
    const user: GetMeResponse | null = await ctx.runQuery(api.queries.users.getMe);

    if (!user) {
      throw new Error("User not found");
    }

    return user;
  },
});


Question:

How can I avoid explicitly defining GetMeResponse | null and let TypeScript infer the types automatically for these Convex query handlers?
Was this page helpful?