Skip to content

Add a type discriminator to result types #1905

@gordonbrander

Description

@gordonbrander

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,

export interface PostgrestResponseSuccess<T> extends PostgrestResponseBase {
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions