The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
docs: update TypeScript Support section on JS reference
Bobbie Soedirgoe274dbf26eef
diff --git a/apps/docs/docs/ref/javascript/typescript-support.mdx b/apps/docs/docs/ref/javascript/typescript-support.mdxindex 51162da7b93..dd555315a84 100644--- a/apps/docs/docs/ref/javascript/typescript-support.mdx+++ b/apps/docs/docs/ref/javascript/typescript-support.mdx@@ -1,23 +1,26 @@---id: typescript-support-title: Typescript Support+title: TypeScript Support----`supabase-js` supports Typescript.+`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](https://www.postgresql.org/docs/current/ddl-generated-columns.html). 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 foreign table with one-to-many relationship is typed as `T[]`. Likewise, a foreign table with many-to-one relationship is typed as `T | null`.## Generating types<RefSubLayout.EducationRow><RefSubLayout.Details>- You can use our CLI to generate types:+ You can use the Supabase CLI to [generate the types](/docs/reference/cli/supabase-gen-types-typescript). You can also generate the types [from the dashboard](https://supabase.com/dashboard/project/_/api?page=tables-intro).</RefSubLayout.Details><RefSubLayout.Examples>```bash Terminal- supabase start- supabase gen types typescript --local > lib/database.types.ts+ supabase gen types typescript --project-id abcdefghijklmnopqrst > database.types.ts```</RefSubLayout.Examples>@@ -26,25 +29,41 @@ title: Typescript Support<RefSubLayout.EducationRow><RefSubLayout.Details>- 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.+ These types are generated from your database schema. Given a table `public.movies`, the generated types will look like:</RefSubLayout.Details><RefSubLayout.Examples>- Given a table `public.movies`, the definition will provide the following data:+ ```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[]- ```ts /types.ts- interface Database {+ export interface Database {public: {Tables: {movies: {- Row: {} // The data expected to be returned from a "select" statement.- Insert: {} // The data expected passed to an "insert" statement.- Update: {} // The data expected passed to an "update" statement.+ 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+ }}}}@@ -54,18 +73,18 @@ title: Typescript Support</RefSubLayout.Examples></RefSubLayout.EducationRow>-## Injecting type definitions+## Using type definitions<RefSubLayout.EducationRow><RefSubLayout.Details>- You can enrich the supabase client with the types you generated with Supabase.+ You can supply the type definitions to `supabase-js` like so:</RefSubLayout.Details><RefSubLayout.Examples>```ts ./index.tsximport { createClient } from '@supabase/supabase-js'- import { Database } from 'lib/database.types'+ import { Database } from './database.types'const supabase = createClient<Database>(process.env.SUPABASE_URL,@@ -76,52 +95,94 @@ title: Typescript Support</RefSubLayout.Examples></RefSubLayout.EducationRow>-## Type hints+## Helper types++You can use the following helper types to make the TypeScript support easier to use.<RefSubLayout.EducationRow><RefSubLayout.Details>- `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:+ 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:</RefSubLayout.Details><RefSubLayout.Examples>- ```ts- export async function getMovies() {- return await supabase.from('movies').select(`id, title`)- }+ ```ts ./database-generated.types.ts+ export type Json = // ...- type MoviesResponse = Awaited<ReturnType<typeof getMovies>>- export type MoviesResponseSuccess = MoviesResponse['data']- export type MoviesResponseError = MoviesResponse['error']+ 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'++ 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+ }+ }+ }+ }+ }+ >+ ```</RefSubLayout.Examples></RefSubLayout.EducationRow>-## Nested tables-<RefSubLayout.EducationRow><RefSubLayout.Details>- For advanced queries such as nested tables, you may want to construct your own types.++ It's convenient to have shorthands for your most-used types.+</RefSubLayout.Details><RefSubLayout.Examples>+ ```ts ./database.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 supabase from '~/lib/supabase'- import type { Database } from '~/lib/database.types'+ // Before π+ let movie: Database['public']['Tables']['movies']['Row'] = // ...- async function getMovies() {- return await supabase.from('movies').select('id, title, actors(\*)')- }+ // After π+ let movie: Tables<'movies'>+ ```- type Actors = Database['public']['tables']['actors']['row']- type MoviesResponse = Awaited<ReturnType<typeof getMovies>>- type MoviesResponseSuccess = MoviesResponse['data'] & {- actors: Actors[]- }+ </RefSubLayout.Examples>+</RefSubLayout.EducationRow>++<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:++ </RefSubLayout.Details>+ <RefSubLayout.Examples>+ ```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 query = supabase.from('movies').select(`id, title`)+ const movies: DbResult<typeof query> = await query```</RefSubLayout.Examples>