supabase-js icon indicating copy to clipboard operation
supabase-js copied to clipboard

Add a type discriminator to result types

Open gordonbrander opened this issue 1 year ago • 5 comments

Description

Adding a type discriminator such as an ok: boolean property to result types such as PostgrestResponseSuccess would make them discriminated unions. This has a number of advantages. You can use if (!res.ok) { ... } to do type narrowing. It also lets the type checker ensure that success and error are mutually exclusive, and there is not some third state of { data: null, error: null }.

Suggested solution

For example, https://github.com/supabase/supabase-js/blob/8d1e0c52c4f3b15e174eddc883611cb5a41c49f0/packages/core/postgrest-js/src/types/types.ts#L15 could become:

export interface PostgrestResponseSuccess<T> extends PostgrestResponseBase {
  ok: true
  error: null
  data: T
  count: number | null
}
export interface PostgrestResponseFailure extends PostgrestResponseBase {
  ok: false
  error: PostgrestError
  data: null
  count: null
}

export type PostgrestSingleResponse<T> = PostgrestResponseSuccess<T> | PostgrestResponseFailure

Alternative

No response

Additional context

Old Typescript handbook doc on discriminating unions https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#discriminating-unions

Validations

gordonbrander avatar Dec 02 '25 11:12 gordonbrander

Hi! Can I take this issue? Just want to confirm the ok: boolean discriminator approach is still acceptable before I start.

nancysangani avatar Dec 03 '25 12:12 nancysangani

A quick note: I was just digging through Zod's docs and noticed that Zod's .safeParse() result type uses the same field names as supabase-js results (data and error). It uses success as the name of the type discriminator field.

type Result<T, E> = {
  success: true;
  data: T;
} | {
  success: false;
  error: E
};

Could be worth using the same field name as Zod?

gordonbrander avatar Dec 03 '25 12:12 gordonbrander

Thanks for the suggestion! Using success as the discriminator makes sense for consistency with Zod. I can implement the change using success: true | false for the response types. Should I proceed with a PR?

nancysangani avatar Dec 03 '25 12:12 nancysangani

(I'm not part of the Supabase team, but I hope the answer is yes)

gordonbrander avatar Dec 03 '25 12:12 gordonbrander

Got it, thanks! I’ll wait for a maintainer to confirm before proceeding with the PR.

nancysangani avatar Dec 03 '25 14:12 nancysangani

Hi! I’d like to work on this issue. Is this approach aligned with the maintainers’ expectations?

selvaganapathycoder avatar Feb 18 '26 09:02 selvaganapathycoder