文档›指南›Generate TypeScript types 从数据库生成 TypeScript 类型
一个命令将您的表转换为类型。然后,您的编辑器会在运行任何操作之前拒绝错误的列或错误的值。
4分钟 读取·级别 初学者·修改于 2026年10月12日
该英文文本是根据法文原文自动生成的,尚未经过审查。
该页面已自动翻译。英文版具有权威性。
terminalbash
npx @aurabase/gen --url https://my-app.aurabase.cloud --key "$AURA_ANON_KEY" --out src/types/database.types.ts
该工具读取项目的架构并写入文件。如果没有 --url 和 --key,它会在您的环境以及 .env、 .env.local 和 .env.development中查找 AURABASE_URL 和 AURABASE_ANON_KEY (还有 NEXT_PUBLIC_AURABASE_URL、 VITE_AURABASE_URL 和 AURABASE_SERVICE_ROLE_KEY)。
在一个有两个表和两个函数的项目中,它回答:
text
[aurabase-gen] ✓ Types écrits dans /tmp/database.types.ts (2 table(s), 2 fonction(s), 0 enum(s), 0 vue(s)).
每当架构更改时再次运行它。添加 --schema <name> 表示除 public之外的架构,并添加 --type-name 来重命名主类型。
src/lib/aurabase.tstypescript
import { createClient } from '@aurabase/aurabase-js'
import type { Database } from '../types/database.types'
export const aura = createClient<Database>(process.env.AURA_URL!, process.env.AURA_ANON_KEY!)
生成的类型使用 Row、 Insert 和 Update描述每个表。针对真实文件,编译器给出了以下结果:
checked.tstypescript
const { data } = await aura.from('todos').select('id, title, done')
const title: string | undefined = data?.[0]?.title // 好的
const wrong: number | undefined = data?.[0]?.title // 错误:字符串不能分配给数字
await aura.from('todos').insert({ title: 1 }) // 错误:数字不可分配给字符串
await aura.from('todos').insert({ title: 'ok' }) // 好的:其他列都有默认值
在 Insert中,具有默认列或可为空列的列是可选的。在 Update中,每一列都是可选的。
Todo.tsxtypescript
import type { Tables, TablesInsert, TablesUpdate, Enums } from '../types/database.types'
type Todo = Tables<'todos'> // 一行,如读
type NewTodo = TablesInsert<'todos'> // insert() 接受什么
type TodoPatch = TablesUpdate<'todos'> // update() 接受什么
Enums<'name'> 给出数据库枚举的值。
- 不在生成文件中的表是 而不是 被拒绝:
aura.from('anything') 仍然可以编译,并且其行是无类型的。
- 函数及其参数出现在
Functions 下。返回自定义行类型的函数显示为 Json 或 unknown。
- 该文件反映了生成它时的架构。在您再次运行该工具之前,稍后添加的列对于类型来说是未知的。
- 使用公钥生成类型,除非某些表对其隐藏。切勿提交
service_role 密钥。