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 referenced table with one-to-many relationship is typed as T[]
. Likewise, a referenced table with many-to-one relationship is typed as T | null
.
Generating TypeScript 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 TypeScript type definitions#
You can supply the type definitions to supabase-js
like so:
Helper types for Tables and Joins#
You can use the following helper types to make the generated TypeScript types 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:
You can also override the type of an individual successful response if needed:
_10const { data } = await supabase.from('countries').select().returns<MyType>()
The generated types provide shorthands for accessing tables and enums.
Response types for complex queries#
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, including nested types for database joins.
Given the following schema with a relation between cities and countries, we can get the nested CountriesWithCities
type:
_10create table countries (_10 "id" serial primary key,_10 "name" text_10);_10_10create table cities (_10 "id" serial primary key,_10 "name" text,_10 "country_id" int references "countries"_10);
_17import { QueryResult, QueryData, QueryError } from '@supabase/supabase-js'_17_17const countriesWithCitiesQuery = supabase_17 .from("countries")_17 .select(`_17 id,_17 name,_17 cities (_17 id,_17 name_17 )_17 `);_17type CountriesWithCities = QueryData<typeof countriesWithCitiesQuery>;_17_17const { data, error } = await countriesWithCitiesQuery;_17if (error) throw error;_17const countriesWithCities: CountriesWithCities = data;