The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type <Restaurant> does not satisfy the constraint 'never'. ts(2344)"

Here is my code snippet:

type Restaurant = {
    id: string;
    name: string;
    categories: string[];
    open: boolean;
    description: string;
  }


const addRestaurant = async () => {
    if (!user.value) return 
    
    const { data, error } = await supabaseClient
      .from('restaurants')
      .upsert<Restaurant>({
        id: user.value.id,
        name: name.value,
        categories: arr,
        open: status.value,
        description: description.value
      })
      .select()
      console.log(data, error);

  }

The error pertains to <Restaurant>, and when I don't specify the type, a similar error occurs stating:

Argument of type '{ id: string; name: string; categories: string; open: boolean; description: string; }' is not assignable to parameter of type 'never[]'. Object literal may only specify known properties, and 'id' does not exist in type 'never[]'.ts(2345)

When hovering over the "upsert()" function, it seems like this is happening in the background:

PostgrestQueryBuilder<never, never>

Any suggestions on how to resolve this?

  • I attempted specifying the Type of the object but realized that the functions [insert, update, upsert] require something else.
  • I found out that adding a second parameter with an empty string temporarily resolves the error. However, modifying anything within it triggers the error again (which shouldn't be the ideal solution).
  • The code functions with or without the second parameter, but the error persists during development - I prefer not to disable Typescript as I want to catch errors early.

Answer №1

In order to resolve the issue, I simply had to generate the types from Supabase. This was achieved by utilizing the Supabase CLI and executing the following command in the terminal:

supabase gen types typescript --project-id

Subsequently, I needed to incorporate the generated types into my Supabase client code like so:

import { createClient } from '@supabase/supabase-js'
import { Database } from 'lib/database.types'

const supabase = createClient<Database>(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_ANON_KEY
)

Answer №2

When using supabase-js, handling types is different than what you might expect. It's important to familiarize yourself with the TypeScript support section in the documentation for a better understanding. If you don't explicitly define a type, errors will only occur if you're passing in values of type never[]. In your code snippet, the absence of a guard clause when accessing user.value.id can cause legitimate errors as it's not always guaranteed to have a value.

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

One-liner in TypeScript for quickly generating an object that implements an interface

In Typescript, you can create an object that implements an interface using a single expression like this: => return {_ : IStudent = { Id: 1, name: 'Naveed' }}; Is it possible to achieve this in just one statement without the need for separate ...

Tips for efficiently awaiting outcomes from numerous asynchronous procedures enclosed within a for loop?

I am currently working on a search algorithm that goes through 3 different databases and displays the results. The basic structure of the code is as follows: for(type in ["player", "team", "event"]){ this.searchService.getSearchResult(type).toPromise ...

What is a way to merge all the letters from every console.log result together?

I'm encountering an issue - I've been attempting to retrieve a string that provides a link to the current user's profile picture. However, when I use console.log(), the output appears as follows: Console Output: Below is my TypeScript code ...

Issue encountered with redux-toolkit's createAsyncThunk functionality

Here is how I implemented the deleteDirectories method in redux: export const deleteDirectories = createAsyncThunk( "directories/deleteDirectories", async (id, thunkAPI) => { try { const response = await axios.delete(`${url}direc ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

Encountering compilation issues when transitioning from Angular 7 to Angular 8

Upon upgrading my project to Angular 8, an unexpected error occurs during the build process: ERROR in HostResourceLoader: loader(C:/myapp/cli/src/app/pages/user-home/user-home.component.html) returned a Promise i 「wdm」: Failed to compile. Ho ...

What is the reason that Jest is not able to spy on the function?

A custom Hook was developed with only one function being imported. Ensuring this function is called with the correct arguments is crucial. import { IsValueAlreadyRegistered } from "../../entities/registration/actions"; export const useForgetPass ...

I am encountering issues with running my tests using react-testing-library alongside TypeScript

Currently facing issues with react-testing-library in my TypeScript-based React project. Despite researching and following various tutorials, I am unable to resolve the problem. I have experimented with changing configurations in babel.config.js, tsconfig ...

The process of removing and appending a child element using WebDriverIO

I am trying to use browser.execute in WebDriverIO to remove a child element from a parent element and then append it back later. However, I keep receiving the error message "stale element reference: stale element not found". It is puzzling because keepin ...

What could be causing this TypeScript class to not perform as anticipated?

My goal with this code snippet is to achieve the following: Retrieve a template using $.get(...), Attach an event listener to the input element within the template I am using webpack to transpile the code without encountering any issues. The actual cod ...

Error with Typescript types when using Styled Components

After successfully setting up styled-components in react-native, I encountered an issue while trying to use it in a simple example with react-native-web: import * as React from 'react'; import styled from 'styled-components'; export d ...

Enhancing the NextPage Typescript Type: A Step-by-Step Guide

I'm working on a NextJS dashboard with role-based access control and I need to pass an auth object to each page from the default export. Here's an image showing an example of code for the Student Dashboard Home Page: Code Example of Student Dashb ...

Having trouble displaying the week number in Angular Highcharts?

I am currently facing an issue with implementing highcharts in my Angular application that I am unable to resolve. My goal is to display the week number on the xAxis using the 'datetime' type. I came across this JSFiddle that seems to provide a ...

Tips for customizing Material UI CSS default properties in React

I'm currently working on a React project and utilizing the 'Table' component from Material UI. The default CSS properties of this table, along with its components like TableHead, TableCell, and TableRow, are proving difficult to override whi ...

Exploring the Capabilities of TypeScript 1.8 in Visual Studio 2017

Recently, I've encountered an issue with my Visual Studio project that was created using TypeScript 1.8 in Visual Studio 2015. Upon upgrading to Visual Studio 2017 and attempting to open the project in the new IDE, I noticed that the TypeScript versio ...

The feature of Nuxt 3's tsconfig path seems to be malfunctioning when accessed from the

Take a look at my file structure below -shared --foo.ts -web-ui (nuxt project) --pages --index.vue --index.ts --tsconfig.json This is the tsconfig for my nuxt setup. { // https://v3.nuxtjs.org/concepts/typescript "exte ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Utilizing Angular 14 and Typescript to fetch JSON data through the URL property in an HTML

Is there a way to specify a local path to a JSON file in HTML, similar to how the src attribute works for an HTML img tag? Imagine something like this: <my-component data-source="localPath"> Here, localPath would point to a local JSON fil ...

Utilize the useState() hook to add an object and display its data in a React Native

Here is a function I am working with: const [dataLoc, setDataLoc] = useState({date: "No data received yet from sensor", coords: {}}); This is where I set the location: Geolocation.getCurrentPosition( location => { const date = d ...

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...