3 Hours

16. Type Safety: TypeScript & Generated Types

TypeScript

End-to-End Type Safety from Database to Frontend

Supabase's type generation gives you TypeScript types derived directly from your PostgreSQL schema. This means if you rename a column in your database migration, your TypeScript compilation will fail — catching breaking changes at build time instead of in production at runtime.

Type safety is one of the biggest benefits of using Supabase with TypeScript. The generated types are a perfect reflection of your schema. If your schema changes, the types change. This catches errors early in the development cycle. The types include Row (what SELECT returns), Insert (what INSERT accepts), and Update (what UPDATE accepts). The Insert type marks columns with defaults as optional, matching what Postgres requires. The Update type marks all fields as optional, since PATCH only updates provided fields. With these types, you can build type-safe queries, type-safe RPC calls, and type-safe error handling. This is the single most effective way to prevent bugs in your application code.

Understanding Generated Types

The generated types are a nested object with the Database type at the top. The Database type has a public schema with Tables and Functions. Each table has Row, Insert, and Update types. Row is the shape of a SELECT result. Insert is the shape of an INSERT payload — optional fields have ? because they have defaults. Update is the shape of a PATCH payload — all fields are optional. The Functions type includes RPC functions with their arguments and return types. Understanding these types is essential for writing type-safe code. You can extract specific types using type lookups. For example, type Post = Database[public][Tables][posts][Row]. This gives you the exact type of a post row.

TypeScript
// Generated file: src/types/database.types.ts (auto-generated, do not edit)
export type Database = {
  public: {
    Tables: {
      posts: {
        Row: { id: string; user_id: string; title: string; body: string | null; published: boolean; };
        Insert: { id?: string; user_id: string; title: string; body?: string | null; published?: boolean; };
        Update: { title?: string; body?: string | null; published?: boolean; };
      };
    };
    Functions: {
      match_documents: {
        Args: { query_embedding: number[]; match_threshold: number; match_count: number };
        Returns: { id: number; content: string; similarity: number }[];
      };
    };
  };
};

Using Types in Practice

With generated types, you get type safety throughout your application. Create a client with the Database type parameter. This enables type checking on all queries. Define reusable type aliases for tables. For example, type Post = Database[public][Tables][posts][Row]. Use this in functions that return posts. For mutations, use the Insert or Update types. For RPC calls, TypeScript validates the arguments. This prevents mismatches between your code and the schema. The type safety catches errors at compile time — before they reach production. This is especially valuable during migrations. When you rename a column, TypeScript shows you all the places that need updating. This eliminates guesswork and manual verification.

TypeScript
import { Database } from '@/types/database.types';

type Post = Database['public']['Tables']['posts']['Row'];
type NewPost = Database['public']['Tables']['posts']['Insert'];

const supabase = createClient<Database>(url, key);

// TypeScript enforces correct field names and types
async function createPost(post: NewPost): Promise<Post> {
  const { data, error } = await supabase
    .from('posts')
    .insert(post)
    .select()
    .single();
  if (error) throw error;
  return data;
}

Helper Type Utilities

Create reusable type aliases from the generated types: type Tables<T extends keyof Database[<strong><code>public][Tables]> = Database[public][Tables][T][Row]. This lets you write Tables<<strong><code>posts> as a shorthand for the full post row type.

Handling Errors with Type Safety

Type safety extends to error handling. The Supabase client returns a result object with data and error fields. You can create a DbResult type that represents this pattern. This ensures you check the error case before accessing data. When you do, TypeScript knows that data is not null. This pattern is more reliable than try/catch because it forces you to handle errors explicitly. The PostgrestError type includes the error message, code, and details. Use this to log errors and show user-friendly messages. This type-safe error handling ensures you never accidentally ignore errors. It's a best practice for production applications.

TypeScript
import { PostgrestError } from '@supabase/supabase-js';

type DbResult<T> = { data: T; error: null } | { data: null; error: PostgrestError };

async function getPosts(): Promise<Post[]> {
  const result: DbResult<Post[]> = await supabase
    .from('posts')
    .select('*')
    .eq('published', true);
  if (result.error) {
    console.error('DB error:', result.error.message, result.error.code);
    throw result.error;
  }
  return result.data;
}

Knowledge Check

Ready to test your understanding of 16. Type Safety: TypeScript & Generated Types?

Back