如何以更简洁方式提取TypeScript深层类型?
抽象TypeScript中的Supabase深层Row类型
针对Supabase生成的Database类型,你可以通过以下几种方式抽象深层的Row类型,简化类型引用:
方式一:直接定义单个类型别名
如果只是高频使用某一个表的Row类型,直接创建类型别名是最简洁的方式:
// 为profiles表的Row类型创建别名 type Profiles = Database['public']['Tables']['profiles']['Row']; // 使用示例 const profiles: Profiles = { email: 'user@example.com', full_name: 'John Doe', id: 'uuid-123', is_complete: false };
方式二:创建表Row类型的映射集合
如果需要访问多个表的Row类型,可以通过映射类型生成一个包含所有表Row类型的集合,通过表名直接索引:
// 自动映射所有public表的Row类型 type TableRows = { [TableName in keyof Database['public']['Tables']]: Database['public']['Tables'][TableName]['Row'] }; // 使用示例 const profiles: TableRows['profiles'] = { /* ... */ }; const project: TableRows['project'] = { /* ... */ }; const service: TableRows['service'] = { /* ... */ };
方式三:通用泛型工具类型(支持多操作类型)
如果还需要同时引用Insert/Update类型,可以定义一个泛型工具类型,灵活指定表名和操作类型:
// 通用工具类型,支持指定表名和操作类型(Row/Insert/Update) type TableOperationType< TableName extends keyof Database['public']['Tables'], Operation extends 'Row' | 'Insert' | 'Update' > = Database['public']['Tables'][TableName][Operation]; // 使用示例 // 获取profiles表的Row类型 const profilesRow: TableOperationType<'profiles', 'Row'> = { /* ... */ }; // 获取profiles表的Insert类型 const profilesInsert: TableOperationType<'profiles', 'Insert'> = { /* ... */ }; // 获取project表的Update类型 const projectUpdate: TableOperationType<'project', 'Update'> = { /* ... */ };
内容的提问来源于stack exchange,提问作者Rokas Rudgalvis
相关产品推荐
相关产品推荐

