如何在Supabase查询结果的map中正确访问关联表属性?
解决Supabase关联表属性访问的TypeScript类型错误
问题背景
现有Supabase查询语句:
const { data, error } = await supabase .from("invoices") .select(`id, customers(name, image_url, email), amount`) .order("date") .limit(5);
需要将查询结果转换为如下TypeScript类型:
export type LatestInvoice = { id: string; name: string; image_url: string; email: string; amount: string; };
使用以下map转换时出现错误:
(该属性不存在于类型 '{name: any; image_url: any; email: any;}[]')
错误的map代码:
const latestInvoices = data?.map( (invoice): LatestInvoice => ({ id: invoice.id, name: invoice.customers.name, image_url: invoice.customers.image_url, email: invoice.customers.email, amount: formatCurrency(invoice.amount), }) );
解决方法
报错核心原因是:Supabase中invoices与customers的关联为一对多关系,查询返回的customers字段是数组类型,而非单个对象,直接通过.name访问自然会触发类型错误。
方案1:调整关联关系为一对一
如果业务逻辑里每个发票仅对应一个客户,可在Supabase控制台的表关系设置中,将invoices到customers的关联改为一对一。修改后查询返回的customers会是单个对象,原map代码无需改动即可正常运行。
方案2:处理数组形式的关联数据
如果业务上确实是一对多关系,或不想修改关联设置,需从customers数组中取出目标元素(通常取第一个),同时用可选链和空值合并处理数组为空的边界情况:
const latestInvoices = data?.map( (invoice): LatestInvoice => ({ id: invoice.id, name: invoice.customers[0]?.name ?? '', image_url: invoice.customers[0]?.image_url ?? '', email: invoice.customers[0]?.email ?? '', amount: formatCurrency(invoice.amount), }) );
若要做更严谨的类型检查,可补充定义Supabase返回数据的类型:
type Customer = { name: string; image_url: string; email: string; }; type SupabaseInvoice = { id: string; customers: Customer[]; amount: number; // 根据实际数据类型调整 }; export type LatestInvoice = { id: string; name: string; image_url: string; email: string; amount: string; };
内容的提问来源于stack exchange,提问作者Ferran
相关产品推荐
相关产品推荐

