Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

docs: Improve docs for joins and TypeScript (#19075)

Thor 雷神 Schaeffe9aea99af6a7
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
index 9a29fded31e..ef0b5fa29b2 100644
--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
@@ -627,6 +627,10 @@ export const database: NavMenuConstant = {
items: [
{ name: 'Connecting to your database', url: '/guides/database/connecting-to-postgres' },
{ name: 'Managing tables, views, and data', url: '/guides/database/tables' },
+ {
+ name: 'Querying joins and nested tables',
+ url: '/guides/api/joins-and-nesting',
+ },
{ name: 'JSON and unstructured data', url: '/guides/database/json' },
{ name: 'Managing database functions', url: '/guides/database/functions' },
{ name: 'Managing indexes', url: '/guides/database/postgres/indexes' },
@@ -807,7 +811,7 @@ export const api: NavMenuConstant = {
{ name: 'Quickstart', url: '/guides/api/quickstart', items: [] },
{ name: 'Client Libraries', url: '/guides/api/rest/client-libs', items: [] },
{ name: 'Auto-generated Docs', url: '/guides/api/rest/auto-generated-docs', items: [] },
- { name: 'Generating Types', url: '/guides/api/rest/generating-types', items: [] },
+ { name: 'Generating TypeScript Types', url: '/guides/api/rest/generating-types', items: [] },
{
name: 'Guides',
url: '/guides/api',
diff --git a/apps/docs/docs/ref/javascript/typescript-support.mdx b/apps/docs/docs/ref/javascript/typescript-support.mdx
index 3bb119fd8be..0a3163d2572 100644
--- a/apps/docs/docs/ref/javascript/typescript-support.mdx
+++ b/apps/docs/docs/ref/javascript/typescript-support.mdx
@@ -9,7 +9,7 @@ With TypeScript, `supabase-js` detects things like `not null` constraints and [g
`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 types
+## Generating TypeScript Types
<RefSubLayout.EducationRow>
<RefSubLayout.Details>
@@ -73,7 +73,7 @@ With TypeScript, `supabase-js` detects things like `not null` constraints and [g
</RefSubLayout.Examples>
</RefSubLayout.EducationRow>
-## Using type definitions
+## Using TypeScript type definitions
<RefSubLayout.EducationRow>
<RefSubLayout.Details>
@@ -95,9 +95,9 @@ With TypeScript, `supabase-js` detects things like `not null` constraints and [g
</RefSubLayout.Examples>
</RefSubLayout.EducationRow>
-## Helper types
+## Helper types for Tables and Joins
-You can use the following helper types to make the TypeScript support easier to use.
+You can use the following helper types to make the generated TypeScript types easier to use.
<RefSubLayout.EducationRow>
<RefSubLayout.Details>
@@ -119,6 +119,7 @@ You can use the following helper types to make the TypeScript support easier to
import { Database as DatabaseGenerated } from './database-generated.types'
export { Json } from './database-generated.types'
+ // Override the type for a specific column in a view:
export type Database = MergeDeep<
DatabaseGenerated,
{
@@ -139,6 +140,21 @@ You can use the following helper types to make the TypeScript support easier to
</RefSubLayout.Examples>
</RefSubLayout.EducationRow>
+<RefSubLayout.EducationRow>
+<RefSubLayout.Details>
+
+You can also override the type of an individual successful response if needed:
+
+</RefSubLayout.Details>
+<RefSubLayout.Examples>
+
+```ts
+const { data } = await supabase.from('countries').select().returns<MyType>()
+```
+
+</RefSubLayout.Examples>
+</RefSubLayout.EducationRow>
+
<RefSubLayout.EducationRow>
<RefSubLayout.Details>
@@ -147,12 +163,17 @@ You can use the following helper types to make the TypeScript support easier to
</RefSubLayout.Details>
<RefSubLayout.Examples>
```ts ./database.types.ts
+ import { Database } from "./database-generated.types.ts";
+ export type { Database } from "./database-generated.types.ts";
+
export type Tables<T extends keyof Database['public']['Tables']> = Database['public']['Tables'][T]['Row']
export type Enums<T extends keyof Database['public']['Enums']> = Database['public']['Enums'][T]
// etc.
```
```ts ./index.ts
+ import { Database, Tables } from "./database.types.ts";
+
// Before 😕
let movie: Database['public']['Tables']['movies']['Row'] = // ...
@@ -163,12 +184,29 @@ You can use the following helper types to make the TypeScript support easier to
</RefSubLayout.Examples>
</RefSubLayout.EducationRow>
+### Response types for complex queries
+
<RefSubLayout.EducationRow>
<RefSubLayout.Details>
`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:
+ 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:
+
+ ```sql
+ create table countries (
+ "id" serial primary key,
+ "name" text
+ );
+
+ create table cities (
+ "id" serial primary key,
+ "name" text,
+ "country_id" int references "countries"
+ );
+ ```
</RefSubLayout.Details>
<RefSubLayout.Examples>
@@ -181,8 +219,18 @@ You can use the following helper types to make the TypeScript support easier to
```
```ts
- const query = supabase.from('movies').select(`id, title`)
- const movies: DbResult<typeof query> = await query
+ const countriesWithCitiesQuery = supabase.from("countries").select(
+ `
+ id,
+ name,
+ cities ( id, name )
+ `
+ );
+ type CountriesWithCities = DbResultOk<typeof countriesWithCitiesQuery>;
+
+ const { data, error } = await countriesWithCitiesQuery;
+ if (error) throw error;
+ const countriesWithCities: CountriesWithCities = data;
```
</RefSubLayout.Examples>
diff --git a/apps/docs/pages/guides/api/joins-and-nesting.mdx b/apps/docs/pages/guides/api/joins-and-nesting.mdx
index 193fa5ecf4d..f8ce890deb2 100644
--- a/apps/docs/pages/guides/api/joins-and-nesting.mdx
+++ b/apps/docs/pages/guides/api/joins-and-nesting.mdx
@@ -89,6 +89,52 @@ const { data, error } = await supabase.from('countries').select(`
`)
```
+### TypeScript Types for Joins
+
+`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:
+
+```sql
+create table countries (
+ "id" serial primary key,
+ "name" text
+);
+
+create table cities (
+ "id" serial primary key,
+ "name" text,
+ "country_id" int references "countries"
+);
+```
+
+We can get the nested `CountriesWithCities` type like this:
+
+```ts
+import { PostgrestError } from '@supabase/supabase-js'
+
+export type DbResult<T> = T extends PromiseLike<infer U> ? U : never
+export type DbResultOk<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never
+export type DbResultErr = PostgrestError
+```
+
+```ts
+const countriesWithCitiesQuery = supabase.from('countries').select(
+ `
+ id,
+ name,
+ cities ( id, name )
+`
+)
+type CountriesWithCities = DbResultOk<typeof countriesWithCitiesQuery>
+
+const { data, error } = await countriesWithCitiesQuery
+if (error) throw error
+const countriesWithCities: CountriesWithCities = data
+```
+
</TabPanel>
<TabPanel id="dart" label="Dart">
diff --git a/apps/docs/pages/guides/api/rest/generating-types.mdx b/apps/docs/pages/guides/api/rest/generating-types.mdx
index b8150d5a218..2f4aad081f9 100644
--- a/apps/docs/pages/guides/api/rest/generating-types.mdx
+++ b/apps/docs/pages/guides/api/rest/generating-types.mdx
@@ -2,7 +2,7 @@ import Layout from '~/layouts/DefaultGuideLayout'
export const meta = {
id: 'generating-types',
- title: 'Generating Types',
+ title: 'Generating TypeScript Types',
description: 'How to generate types for your API and Supabase libraries.',
subtitle: 'How to generate types for your API and Supabase libraries.',
tocVideo: '/7CqlTU9aOR4',
@@ -32,24 +32,171 @@ Generate types for your project to produce the `types/supabase.ts` file:
npx supabase gen types typescript --project-id "$PROJECT_REF" --schema public > types/supabase.ts
```
-After you have generated your types, you can use them in `src/index.ts`
+These types are generated from your database schema. Given a table `public.movies`, the generated types will look like:
-```tsx
-import { NextApiRequest, NextApiResponse } from 'next'
+```sql
+create table public.movies (
+ id bigint generated always as identity primary key,
+ name text not null,
+ data jsonb null
+);
+```
+
+```ts ./database.types.ts
+export type Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[]
+
+export interface Database {
+ public: {
+ Tables: {
+ movies: {
+ Row: {
+ // the data expected from .select()
+ id: number
+ name: string
+ data: Json | null
+ }
+ Insert: {
+ // the data to be passed to .insert()
+ id?: never // generated columns must not be supplied
+ name: string // `not null` columns with no default must be supplied
+ data?: Json | null // nullable columns can be omitted
+ }
+ Update: {
+ // the data to be passed to .update()
+ id?: never
+ name?: string // `not null` columns are optional on .update()
+ data?: Json | null
+ }
+ }
+ }
+ }
+}
+```
+
+## Using TypeScript type definitions
+
+You can supply the type definitions to `supabase-js` like so:
+
+```ts ./index.tsx
import { createClient } from '@supabase/supabase-js'
-import { Database } from '../types/supabase'
+import { Database } from './database.types'
-const supabase = createClient<Database>(
- process.env.NEXT_PUBLIC_SUPABASE_URL,
- process.env.SUPABASE_SECRET_KEY
-)
+const supabase = createClient<Database>(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY)
+```
+
+## Helper types for Tables and Joins
-export default async (req: NextApiRequest, res: NextApiResponse) => {
- const allOnlineUsers = await supabase.from('users').select('*').eq('status', 'ONLINE')
- res.status(200).json(allOnlineUsers)
+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](https://github.com/sindresorhus/type-fest), you can override the types like so:
+
+```ts ./database-generated.types.ts
+export type Json = // ...
+
+export interface Database {
+ // ...
}
```
+```ts ./database.types.ts
+import { MergeDeep } from 'type-fest'
+import { Database as DatabaseGenerated } from './database-generated.types'
+export { Json } from './database-generated.types'
+
+// Override the type for a specific column in a view:
+export type Database = MergeDeep<
+ DatabaseGenerated,
+ {
+ public: {
+ Views: {
+ movies_view: {
+ Row: {
+ // id is a primary key in public.movies, so it must be `not null`
+ id: number
+ }
+ }
+ }
+ }
+ }
+>
+```
+
+You can also override the type of an individual successful response if needed:
+
+```ts
+const { data } = await supabase.from('countries').select().returns<MyType>()
+```
+
+### Type shorthands
+
+It's convenient to have shorthands for your most-used types.
+
+```ts ./database.types.ts
+import { Database } from './database-generated.types.ts'
+export type { Database } from './database-generated.types.ts'
+
+export type Tables<T extends keyof Database['public']['Tables']> =
+ Database['public']['Tables'][T]['Row']
+export type Enums<T extends keyof Database['public']['Enums']> = Database['public']['Enums'][T]
+// etc.
+```
+
+```ts ./index.ts
+import { Database, Tables } from "./database.types.ts";
+
+// Before 😕
+let movie: Database['public']['Tables']['movies']['Row'] = // ...
+
+// After 😍
+let movie: Tables<'movies'>
+```
+
+### 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:
+
+```sql
+create table countries (
+ "id" serial primary key,
+ "name" text
+);
+
+create table cities (
+ "id" serial primary key,
+ "name" text,
+ "country_id" int references "countries"
+);
+```
+
+We can get the nested `CountriesWithCities` type like this:
+
+```ts
+import { PostgrestError } from '@supabase/supabase-js'
+
+export type DbResult<T> = T extends PromiseLike<infer U> ? U : never
+export type DbResultOk<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never
+export type DbResultErr = PostgrestError
+```
+
+```ts
+const countriesWithCitiesQuery = supabase.from('countries').select(
+ `
+ id,
+ name,
+ cities ( id, name )
+`
+)
+type CountriesWithCities = DbResultOk<typeof countriesWithCitiesQuery>
+
+const { data, error } = await countriesWithCitiesQuery
+if (error) throw error
+const countriesWithCities: CountriesWithCities = data
+```
+
## 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.