supabase / postgrest-js

Isomorphic JavaScript client for PostgREST.
https://supabase.com
MIT License
964 stars 128 forks source link

Wrong type inference for particular join (between a superclass and a subclass) #477

Closed gareth618 closed 6 months ago

gareth618 commented 9 months ago

Bug report

Context

Our application stores a table called partners. Since our partners can be either individual or legal persons, and we store different data for each of these two types of partners, we created two new tables: indiv_partners and legal_partners.

The primary key of partners is id, while the primary keys of indiv_partners and legal_partners are both called id_partner and reference the id column of partners.

We would like to write a query that retrieves the names of all the partners. That is, if the current partner is an individual, then we want its first_name and last_name fields. However, if it is a legal person, then we just want its name field. Thus, we start with the following code:

const { data } = await supabase
  .from('partners')
  .select('indiv_partners(first_name, last_name), legal_partners(name)')

Bug description

The problem is that the type of data gets inferred incorrectly as:

const data: {
  indiv_partners: {
    first_name: string
    last_name: string
  }[]
  legal_partners: {
    name: string
  }[]
}[] | null

Expected behavior

The right type should be:

const data: {
  indiv_partners: {
    first_name: string
    last_name: string
  } | null
  legal_partners: {
    name: string
  } | null
}[] | null

This is confirmed by the fact that Supabase actually returns an object of this shape (according to my tests).

Screenshots

The wrong type inference:

ts
gareth618 commented 6 months ago

The problem seems to be gone thanks to some new version of the package!