Generating TypeScript Types
How to generate types for your API and Supabase libraries.
Supabase APIs are generated from your database, which means that we can use database introspection to generate type-safe API definitions.
Generating types from project dashboard
Supabase allows you to generate and download TypeScript types directly from the project dashboard.
Generating types using Supabase CLI
The Supabase CLI is a single binary Go application that provides everything you need to setup a local development environment.
You can install the CLI via npm or other supported package managers. The minimum required version of the CLI is v1.8.1.
Login with your Personal Access Token:
Before generating types, ensure you initialize your Supabase project:
Generate types for your project to produce the types/supabase.ts
file:
or in case of local development:
These types are generated from your database schema. Given a table public.movies
, the generated types will look like:
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:
To use MergeDeep
, set compilerOptions.strictNullChecks
to true
in your tsconfig.json
.
You can also override the type of an individual successful response if needed:
Type shorthands
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 like this:
Update types automatically with GitHub Actions
One way to keep your type definitions in sync with your database is to set up a GitHub action that runs on a schedule.
Add the script above to your package.json
to run it using npm run update-types
Create a file .github/workflows/update-types.yml
with the following snippet to define the action along with the environment variables. This script will commit new type changes to your repo every night.
Alternatively, you can use a community-supported GitHub action: generate-supabase-db-types-github-action.