Typescript Support

supabase-js supports Typescript.

Generating types#

You can use our CLI to generate types:

supabase start
supabase gen types typescript --local > lib/database.types.ts

These types are generated directly from your database. Given a table public.movies, the definition will provide the following data:

1interface Database {
2  public: {
3    Tables: {
4      movies: {
5        Row: {} // The data expected to be returned from a "select" statement.
6        Insert: {} // The data expected passed to an "insert" statement.
7        Update: {} // The data expected passed to an "update" statement.
8      }
9    }
10  }

There is a difference between selects, inserts, and updates, because often you will set default values in your database for specific columns. With default values you do not need to send any data over the network, even if that column is a "required" field. Our type system is granular enough to handle these situations.

Injecting type definitions#

You can enrich the supabase client with the types you generated with Supabase.

1import { createClient } from '@supabase/supabase-js'
2import { Database } from 'lib/database.types'
4const supabase = createClient<Database>(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY)

Type hints#

supabase-js always returns a data object (for success), and an error response (for unsuccessful requests). This provides a simple interface to get the relevant types returned from any function:

1export async function getMovies() {
2  return await supabase.from('movies').select(`id, title`)
5type MoviesResponse = Awaited<ReturnType<typeof getMovies>>
6export type MoviesResponseSuccess = MoviesResponse['data']
7export type MoviesResponseError = MoviesResponse['error']

Nested tables#

For advanced queries such as nested tables, you may want to construct your own types.

1import supabase from '~/lib/supabase'
2import type { Database } from '~/lib/database.types'
4async function getMovies() {
5  return await supabase.from('movies').select('id, title, actors(*)')
8type Actors = Database['public']['Tables']['actors']['Row']
9type MoviesResponse = Awaited<ReturnType<typeof getMovies>>
10type MoviesResponseSuccess = MoviesResponse['data'] & {
11  actors: Actors[]