An illuminated red road work cone

Caveat when using the RPC function with Supabase

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.

I saw the first issue in the datatable’s columns definition where TypeScript was telling me that the properties of AllEntitiesType didn’t exist.

The Cause

Supabase’s RPC returns the correct type according to the Postgres 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 made sense to me.

But how do I fix the TypeScript errors?

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 (See rule ts(2352)).

Next, replace all references of AllEntitiesTypes to EntityRecordWithRpc.

Finish with another run of the build script. It should show resolution of all 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