Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query

I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem.

Helper Types Overview:

Below are the helper types I've defined along with their descriptions:

  • DbResult<T>: This type is designed to extract the resolved type from a promise. It determines the type U that the promise resolves to if T is a promise.

  • DbResultOk<T>: This type manages successful query results by inferring the data field from the promise and excluding any null values.

  • DbResultErr: This type is a straightforward alias for PostgrestError, meant to handle errors from Supabase queries.

export type DbResult<T> = T extends PromiseLike<infer U> ? U : never;
export type DbResultOk<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never;
export type DbResultErr = PostgrestError;

Code Implementation:

In my function where I execute a Supabase query, I utilize these types:

export async function addFrequentIngresoAccion(payload: {
  // ... payload definition
}): Promise<DbResult<any>> {
  const supabase = createServerActionClient<Database>({ cookies });
  const query = supabase.from("FuenteIngreso").insert([/*...*/]).select();
  const result: DbResult<typeof query> = await query;

  if (result.error) {
    const resultErr: DbResultErr = result.error;
    return { error: resultErr };
  }

  const resultOk: DbResultOk<Tables<"FuenteIngreso">[]> = result.data as Tables<"FuenteIngreso">[];
  return { data: resultOk };
}

The error message

Type '{ CantidadIngresoRecurrente: number | null; created_at: string; es_recurrente: boolean | null; fechadepositorecurrente: string | null; fuente_name: string; id: number; LastIngresoAdded: string | null; user_id: string; }[]' is not assignable to type 'never'.ts(2322)
is triggered by the line
const resultOk: DbResultOk<Tables<"FuenteIngreso">[]>> = result.data as Tables<"FuenteIngreso">>[];
. I'm puzzled as to why it defaults to never. Any insights on what might be causing this issue would be greatly appreciated. Also, corrections or clarifications on the helper types concept would be welcomed.

Answer №1

Today, I came across this same issue unexpectedly. It turned out to be related to the return value of a Supabase Postgres Function instead of a table. However, the suggested change should resolve your issue or at least bring you very close to a solution.

Replace this line:

const resultOk: DbResultOk<Tables<"FuenteIngreso">[]> = result.data as Tables<"FuenteIngreso">[];

with this:

const resultOk: DbResultOk<typeof query> = result.data

Why make this change?

The definition of DbResultOk is as follows:

export type DbResultOk<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never

This closely resembles the definition of DbResult:

export type DbResult<T> = T extends PromiseLike<infer U> ? U : never

In both definitions, generic type T refers to the data within the query Result object. In short, it is necessary for it to also be typeof query like DbResult because T must extend PromiseLike<>.

This concept falls under Conditional Types in TypeScript, and further information can be found in the TypeScript documentation at: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Warning: The TypeScript version in use may not support all features. The current language level is set to XX in Visual Studio 2019

After installing VS 2019, I noticed that Microsoft.TypeScript.MSBuild 4.2.3 was added. On my Windows 10 OS, I also installed it using NPM in the following way: However, upon opening VS 2019, I encountered the warning below: TypeScript 3.4 feature Curre ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

The Proper Way to Position _app.tsx in a Next.js Setup for Personalized App Configuration

I've been working on a Next.js project and I'm currently trying to implement custom app configuration following the guidelines in the Next.js documentation regarding _app.tsx. However, I'm encountering some confusion and issues regarding the ...

Angular form requests can utilize the Spring Security Jwt Token to allow all options methods

Despite checking numerous sources online, I am facing a persistent issue with my Angular application. The problem arises when using HttpClient along with an Angular interceptor to set headers for authentication in my Java Rest API using JWT tokens. The int ...

Implementing a Set polyfill in webpack fails to address the issues

Encountering "Can't find variable: Set" errors in older browsers during production. Assumed it's due to Typescript and Webpack leveraging es6 features aggressively. Shouldn't be a problem since I've successfully polyfilled Object.assign ...

What is the reason behind Angular 2's choice to implement the .ts file extension?

What is the significance of using the .ts file extension in Angular 2? ...

Tips on exporting TRPC router type to another project

Currently working on a project in typescript with the next.js framework. I am also utilizing trpc/server. Additionally, I am developing a project in vite.js and aiming to incorporate the trpc router type, specifically appRouter. Encountering an issue wher ...

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...

Testing a React component that utilizes the "useQuery" hook outside of the ApolloProvider can be achieved by setting the "client" as an option. This method ensures thorough testing of the

Recently, I decided to make the switch to an SSR app using Next.js after coming across this "official" blog post. The key difference is that components utilizing Apollo are not wrapped in an ApolloProvider. Instead, the "client" serves as a singleton that ...

The absence of the import no longer causes the build to fail

Recently, after an update to the yup dependency in my create react-app project, I noticed that it stopped launching errors for invalid imports. Previously, I would receive the error "module filename has no exported member X" when running react-scripts buil ...

Retrieving data from notifications without having to interact with them (using Firebase Cloud Messaging and React Native)

Currently, I am able to handle messages whether the app is open, minimized, or closed. However, how can I process a message if a user logs into the application without receiving a notification? useEffect(() => { messaging().setBackgroundMessageHa ...

Ways to retrieve the current URL in Next.js without relying on window.location.href or React Router

Is there a way to fetch the current URL in Next.js without relying on window.location.href or React Router? const parse = require("url-parse"); parse("hostname", {}); console.log(parse.href); ...

Setting the port for Next.js on PM2 involves configuring the ecosystem file in the project

I am currently working on a standard next js application and have the following scripts in my package.json file. "scripts": { "dev": "next dev", "build": "next build", "start": " ...

VS Code is throwing an Error TS7013, while Typescript remains unfazed

In my Typescript/Angular project, I have the following interface: export interface MyInterface { new (helper: MyInterfaceHelpers); } After compiling the project, no errors are shown by the Typescript compiler. However, VSCode highlights it with squiggl ...

Discovering the true nature of a generic Type in TypeScript

Consider this scenario involving TypeScript interface IApiCall<TResponse> { method: string; url: string; } Above interface is utilized in the following method; const call = <TResponse>(api: IApiCall<TResponse>): void => { ...

Any ideas on how to fix the issue of 'type' property being absent in 'AsyncThunkAction' with Redux Toolkit while working with TypeScript?

While working with Redux Toolkit and the thunk/slice below, I decided to handle errors locally instead of setting them in state. To achieve this, I followed the example provided here. Although I could have set an error in the state, I wanted to explore wh ...

While attempting to deploy on Vercel, I encountered an error while constructing my Next.js project

While working on my Next login signup project, I encountered the following error: WagmiProviderNotFoundError: `useConfig` must be used within `WagmiProvider`. The documentation for this issue can be found <a href="https://wagmi.sh/react/api/WagmiProvide ...

Unusual host value being returned by next/headers in Next.js version 13

In my current Next.js project, I am utilizing next/headers to dynamically set a baseUrl for calls to my API. const baseUrl = () => { const protocol = process?.env.NODE_ENV === "development" ? "http" : "https"; const ...

Using TypeScript in the current class, transform a class member into a string

When converting a class member name to a string, I rely on the following function. However, in the example provided, we consistently need to specify the name of the Current Component. Is there a way to adjust the export function so that it always refers ...

Enforcing Type Safety on String Enums in Typescript Using the 'const' Assertion

I am trying to use an enum for type checking purposes. Here is the enum I have: enum Options { Option1 = "xyz", Option2 = "abc" } My goal is to create a union type of 'xyz' | 'abc'. However, when I attempt to d ...