Skip to content
DatabaseChapter 34 / 57Intermediate5 min read

Generated Database Types

Generated database types typescript mein, row types schema se banayein, haath se nahi, taake column rename par build fail ho aur production mein undefined na aaye.

On this page

1. Yeh practice kya hai?

Database ka schema sach hai. TypeScript ki type us sach ki tasveer hai. Haath se banayi tasveer purani ho jati hai, generated tasveer har dafa schema se dobara banti hai.

Har bara tool yeh deta hai: Supabase CLI gen types, Drizzle ka $inferSelect, Prisma ka generated client, Kysely ke codegen tools.

2. Kyun zaroori hai?

Migration ne phone ko phone_number kar diya. Haath se likhi User type mein abhi bhi phone hai. TypeScript khush, build green, deploy ho gaya. Production mein har user ka phone undefined, aur signup form ka insert fail kyunki phone column ab mojood hi nahi.

Ulta bhi hota hai: ek column nullable tha, type mein string likha gaya. Code ne .toLowerCase() call kiya aur pehli null value par crash.

Haath se likhi typesGenerated types
Column rename par code compile hota rehta haiColumn rename par build fail hota hai
Nullable column ko string likh diyaGenerated type mein null saaf likha hota hai
Har developer apni copy banata haiEk file, sab wahi import karte hain
Schema aur type dheere dheere alagCI check karta hai ke file schema se match kare
Insert mein required column bhool jate hainInsert type required columns maangti hai

3. Kab follow karein?

LevelKitna zarooriKyun
Learning projectAchha, setup ek command ka haiShuru se type safety ka maza aata hai
Production codeLazmiSchema drift ke bugs sirf runtime par dikhte hain
Senior levelCI check aur derive karne ka andaz tay karnaPoori team ek hi source of truth par chale

Kab seekhein: jab aap pehli dafa TypeScript project ko database se jodein. Strict Typing pehle samajh lein.

4. Bura vs acha code

Bura: haath se row type

ts
export interface User {
  id: string;
  name: string;
  phone: string;
  createdAt: Date;
}

const { data } = await supabase.from("users").select("*");
const users = data as User[];

Database mein phone_number hai aur created_at string aata hai, lekin type kuch aur kehti hai. as ne compiler ki aankhein band kar din.

Acha: Supabase generated types

Command, har migration ke baad:

bash
npx supabase gen types typescript --local > lib/supabase/database.types.ts

Derive karein, dobara likhein nahi:

ts
import type { Database } from "@/lib/supabase/database.types";

type UsersTable = Database["public"]["Tables"]["users"];

export type UserRow = UsersTable["Row"];
export type NewUser = UsersTable["Insert"];
export type UserPatch = UsersTable["Update"];

export type PublicProfile = Pick<UserRow, "id" | "name" | "avatar_url">;

Client ko generated Database dein, taake har query typed ho:

ts
const supabase = createServerClient<Database>(url, anonKey, { cookies: cookieAdapter });

const { data } = await supabase.from("users").select("id, name, phone_number");

Ab agar migration phone_number ka naam badle aur types regenerate hon, to yeh line compile error degi.

Acha: Drizzle mein schema hi source hai

ts
import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: uuid("id").primaryKey().defaultRandom(),
  name: text("name").notNull(),
  phoneNumber: text("phone_number"),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});

export type UserRow = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;

Farq kya hai?

CheezBuraAcha
SourceDeveloper ki yaadDatabase schema
RenameRuntime par undefinedCompile error
NullChhup jata haistring | null saaf
InsertKoi check nahiInsert type required fields maangti hai
Castas User[]Typed client, cast ki zaroorat nahi

5. Kaise apply karein?

Types ka safar
Migration likho
Local database par apply karo
Types regenerate karo, usi PR mein commit
Code compile errors theek karo
CI dobara generate kar ke diff check kare

CI mein ek chhota step jo yaad dilaye:

bash
npx supabase gen types typescript --local > lib/supabase/database.types.ts
git diff --exit-code lib/supabase/database.types.ts

Agar file badli to matlab kisi ne migration ke baad types regenerate nahi kin, aur build fail ho jata hai.

6. Exceptions aur common mistakes

Har type generate nahi hoti. Jo shape kai tables se mil kar bane (jaise dashboard ka summary), ya jo kabhi database tak pohanchti hi nahi (jaise form ka draft), us ke liye apni type banana theek hai. Lekin us mein bhi fields generated types se Pick karein jahan mumkin ho. API contract bhi apni alag shape rakh sakta hai, mapper ke zariye, taake snake_case naam client tak na jayein.

Galati: Generated file ko haath se edit karna

Why? Agli dafa regenerate hote hi aap ki tabdeeli ghayab ho jati hai aur bug wapas aa jata hai.

Behtar: Generated file ko kabhi na chhoo, zaroorat ho to alag file mein us se derive karo.

Galati: Migration aur types alag PRs mein

Why? Beech ke waqt mein main branch par code aur schema match nahi karte aur doosron ka build tootta hai.

Behtar: Migration aur regenerated types hamesha ek hi pull request mein.

Galati: Query result ko as se cast karna

Why? Typed client hote hue bhi cast compiler ko chup kara deta hai aur generated types ka faida khatam.

Behtar: Client ko Database generic do aur select se khud sahi type aane do.

7. Pehle aur baad mein kya seekhein?

Final quick revision

CheckSawal
SourceKya koi row type haath se likhi hui hai?
DeriveKya domain types Row, Insert, Update se bani hain?
RegenerateKya har migration ke saath types usi PR mein?
CIKya CI generated file ka diff check karta hai?
CastKya query results par as lagaya gaya?