Query
I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem.
Helper Types Overview:
Below are the helper types I've defined along with their descriptions:
DbResult<T>
: This type is designed to extract the resolved type from a promise. It determines the typeU
that the promise resolves to ifT
is a promise.DbResultOk<T>
: This type manages successful query results by inferring thedata
field from the promise and excluding anynull
values.DbResultErr
: This type is a straightforward alias forPostgrestError
, meant to handle errors from Supabase queries.
export type DbResult<T> = T extends PromiseLike<infer U> ? U : never;
export type DbResultOk<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never;
export type DbResultErr = PostgrestError;
Code Implementation:
In my function where I execute a Supabase query, I utilize these types:
export async function addFrequentIngresoAccion(payload: {
// ... payload definition
}): Promise<DbResult<any>> {
const supabase = createServerActionClient<Database>({ cookies });
const query = supabase.from("FuenteIngreso").insert([/*...*/]).select();
const result: DbResult<typeof query> = await query;
if (result.error) {
const resultErr: DbResultErr = result.error;
return { error: resultErr };
}
const resultOk: DbResultOk<Tables<"FuenteIngreso">[]> = result.data as Tables<"FuenteIngreso">[];
return { data: resultOk };
}
The error message
Type '{ CantidadIngresoRecurrente: number | null; created_at: string; es_recurrente: boolean | null; fechadepositorecurrente: string | null; fuente_name: string; id: number; LastIngresoAdded: string | null; user_id: string; }[]' is not assignable to type 'never'.ts(2322)
is triggered by the line const resultOk: DbResultOk<Tables<"FuenteIngreso">[]>> = result.data as Tables<"FuenteIngreso">>[];
. I'm puzzled as to why it defaults to never
. Any insights on what might be causing this issue would be greatly appreciated. Also, corrections or clarifications on the helper types concept would be welcomed.