Home

Typescript Support

supabase-js supports Typescript.

Generating types#

You can use our CLI to generate types:

Terminal

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

These types are generated directly from your database.

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.

Given a table public.movies, the definition will provide the following data:

/types.ts

_11
interface Database {
_11
public: {
_11
Tables: {
_11
movies: {
_11
Row: {} // The data expected to be returned from a "select" statement.
_11
Insert: {} // The data expected passed to an "insert" statement.
_11
Update: {} // The data expected passed to an "update" statement.
_11
}
_11
}
_11
}
_11
}

Injecting type definitions#

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

./index.tsx

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

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:


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

Nested tables#

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

./index.ts

_12
import supabase from '~/lib/supabase'
_12
import type { Database } from '~/lib/database.types'
_12
_12
async function getMovies() {
_12
return await supabase.from('movies').select('id, title, actors(\*)')
_12
}
_12
_12
type Actors = Database['public']['tables']['actors']['row']
_12
type MoviesResponse = Awaited<ReturnType<typeof getMovies>>
_12
type MoviesResponseSuccess = MoviesResponse['data'] & {
_12
actors: Actors[]
_12
}