Typescript Support
supabase-js
has TypeScript support for type inference, autocompletion, type-safe queries, and more.
With TypeScript, supabase-js
detects things like not null
constraints and generated columns. Nullable columns are typed as T | null
when you select the column. Generated columns will show a type error when you insert to it.
supabase-js
also detects relationships between tables. A foreign table with one-to-many relationship is typed as T[]
. Likewise, a foreign table with many-to-one relationship is typed as T | null
.
Generating types#
You can use the Supabase CLI to generate the types. You can also generate the types from the dashboard.
These types are generated from your database schema. Given a table public.movies
, the generated types will look like:
_10create table public.movies (_10 id bigint generated always as identity primary key,_10 name text not null,_10 data jsonb null_10);
Using type definitions#
You can supply the type definitions to supabase-js
like so:
Helper types#
You can use the following helper types to make the TypeScript support easier to use.
Sometimes the generated types are not what you expect. For example, a view's column may show up as nullable when you expect it to be not null
. Using type-fest, you can override the types like so:
It's convenient to have shorthands for your most-used types.
supabase-js
always returns a data
object (for success), and an error
object (for unsuccessful requests).
These helper types provide the result types from any query:
_10import { PostgrestError } from '@supabase/supabase-js'_10_10export type DbResult<T> = T extends PromiseLike<infer U> ? U : never_10export type DbResultOk<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never_10export type DbResultErr = PostgrestError
_10const query = supabase.from('movies').select(`id, title`)_10const movies: DbResult<typeof query> = await query