Illuminated road work cone in the dark

Caveat With RPC Supabase Function

Using the RPC method on the Supabase client requires an additional step and TypeScript is involved.

On January 27th, I shared a tip to use Postgres functions to perform an advanced ordering on a table.

Let me show you the error I didn’t catch right away.

The Issue

On all the code related to the allEntitiesQuery, many TypeScript errors showed up.

This first I saw happened to be on the datable columns definition where TypeScript was telling me that the properties of AllEntitiesType didn’t.

The Cause

Supabase’s RPC returns the type according to the function’s return type, as defined in your database schema (source).

In my case, I set RETURNS SETOF json AS $$ and so it did:

Since you can call the function with the table name as an input parameter, the returned type makes sense to me.

But this type is too vague for TypeScript to infer object properties.

The Fix

To fix this, you need to use Supabase generated types and create a new custom type:

1
2
3
4
import type { Database } from "@/types/DatabaseTypes";

export type EntityRecordWithRpc =
  Database["public"]["Tables"]["entities"]["Row"];

Then, you update the returned type to as unknown as PostgrestSingleResponse<EntityRecordWithRpc[]> on the allEntitiesQuery.

The TypeScript requires the as unknown cast first before the as PostgrestSingleResponse<EntityRecordWithRpc[]> because neither type sufficiently overlaps with the other (rule ts(2352)).

Next, replace all references of AllEntitiesTypes to EntityRecordWithRpc.

Finish with another run of the build script and no TypeScript errors!

Conclusion

My takeaway: I need to add a CI step to run the npm run build on each PR. A topic for another article. Stay tuned!

Follow me

Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.

Photo by Mido Makasardi ©️

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy