Encountering a bug in Typescript where a Prisma relation list field fails when provided with an argument

While attempting to initiate a new project using Prisma Client, I encountered an error when passing it with args, even when using an empty array list such as [].

Here is the Prisma model:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Project {
    id String @id @default(cuid())
    name String
    date DateTime @default(now())
    createdAt DateTime @default(now())
    updatedAt DateTime @default(now())
    type String
    client String?
    images Image[]
}

model Image {
    id String @id @default(cuid())
    createdAt DateTime @default(now())
    updatedAt DateTime @default(now())
    title String?
    alt String?
    description String?
    src String
    project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
    projectId String
}

And here is the TypeScript type:

export interface Project {
    name: string;
    date: Date;
    type: string;
    client: string;
    images?: Image[];
}

export interface Image {
    title: string;
    alt: string;
    description: string;
    src: string;
    projectId?: string;
}

Below is my mutation:

Attempt 1

createProject: async (args: Project) => {
  const project = await prisma.project.create({
    data: {
      client: args.client,
      date: args.date,
      name: args.name,
      type: args.type,
      images: args.images
    }
  })
}

Attempt 2

createProject: async (args: Project) => {
  const project = await prisma.project.create({
    data: {
      client: args.client,
      date: args.date,
      name: args.name,
      type: args.type,
      images: []
    }
  })
}

Attempt 3

createProject: async (args: Project & { images?: Image[] }) => {
  const project = await prisma.project.create({
    data: {
      client: args.client,
      date: args.date,
      name: args.name,
      type: args.type,
      images: args.images
    }
  })
}

Additionally, here is the error from the Prisma client:

Type 'Image[] | undefined' is not assignable to type 'ImageUncheckedCreateNestedManyWithoutProjectInput | ImageCreateNestedManyWithoutProjectInput | undefined'. Type 'Image[]' is not assignable to type 'ImageUncheckedCreateNestedManyWithoutProjectInput | ImageCreateNestedManyWithoutProjectInput | undefined'.ts(2322)


index.d.ts(3077, 5): The expected type comes from property 'images' which is declared here on type '(Without<ProjectCreateInput, ProjectUncheckedCreateInput> & ProjectUncheckedCreateInput) | (Without<...> & ProjectCreateInput)' (property) images: Image[] | undefined

If you have any best practices on generating TypeScript types based on the Prisma model, I would greatly appreciate the guidance. Thank you in advance!

Answer №1

After running npx prisma generate, you can directly import the types from Prisma.

import { Post, User } from "@prisma/client"

To get more detailed types for your models, simply open the file where they are defined.

node_modules/.prisma/client/index.d.ts

Within this file, you'll find a variety of types that you can use for specific purposes.

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

How can I configure nginx to direct each domain name to a specific page within my Next.js application?

I encountered an issue with redirecting domain names to a specific page in my Next.js app using Nginx. Currently, my Next.js app is running on localhost:3000 and I attempted to utilize Nginx for domain name redirection. When I pointed a domain name to &ap ...

The issue of Headless UI Transition not functioning properly in conjunction with Dialog components

I have encountered an issue with the transition effect in my Next.js 13 project using Headless UI. The transition effect seems to work only when the element leaves, but not when it enters. I am unsure if this is a bug in the code or if I am missing somethi ...

Tips for resolving the issue with the 'search input field in the header' across all pages in angular 5 with typescript

I currently have a search field in the header that retrieves a list of records when you type a search term and click on one of them. The search function utilizes debounceTime to reduce API requests, but I'm encountering an issue where the search doesn ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

What is the best way to terminate a Node.js app using a scheduler?

I've been attempting to halt my cron task and shut down the entire nodeapp after 5 executions, but despite trying various methods, all attempts have failed. The message "time to quit" continues to appear in the log every minute. What would be the mos ...

Is there a way to ensure in TypeScript that a generic type includes a property that implements a particular method?

To better explain my query, let me provide an illustration. Suppose I aim to create a method that accepts three parameters, as shown below: customFilter<T>(values: T[], filterString: string, propName: string) any[] { return values.filter((value) ...

The issue with Angular2 Material select dropdown is that it remains open even after being toggled

Exploring the world of Node.js, I am delving into utilizing the dropdown feature from Angular Material. However, an issue arises once the dropdown is opened - it cannot be closed by simply clicking another region of the page. Additionally, the dropdown lis ...

Filtering based on the boolean value of a checkbox in Angular

I'm struggling to implement a boolean filter for my search results, separating users with financial debt from those without. I need some guidance on how to achieve this. Data Filter @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Assignment of type 'Angular Promise<void>' is not compatible

In the process of developing a website with Angular4 and retrieving data from Contentful CMS API, I am encountering an issue with assigning proper types to the returned data despite seeing the correct types in the console. The example mock data is as foll ...

Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background: import { Scene, PerspectiveCamera, WebGLRenderer, ...

The union type cannot function effectively in a closed-off environment

Here is the code snippet I am working with: if (event.hasOwnProperty('body')) { Context.request = JSON.parse(event.body) as T; } else { Context.request = event; } The variable event is defined as follows: private static event: aws.IGateway ...

Utilizing Angular 4's piping feature to manipulate data sourced from an API observable within

I am currently working on setting up a filter for my stories. After subscribing to the API call, I receive the data in the form of an array of objects. However, I am encountering an error while trying to apply filters. Here is a snippet of relevant inform ...

What role does AppProps play in the Next.js framework?

As I delve into next.js, I stumbled upon the following snippet in the _app.tsx file: import type { AppProps } from 'next/app' function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } export default MyAp ...

"Overcoming obstacles in managing the global state of a TypeScript preact app with React/Next signals

Hello, I recently attempted to implement a global app state in Preact following the instructions provided in this documentation. However, I kept encountering errors as this is my first time using useContext and I suspect that my configuration might be inco ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

Executing getServerSideProps twice and returning an object during the second invocation

I encountered a problem with my next.js app. It seems that one of the pages is making two calls to getServerSideProps, and on the second call, it returns a string value of "[object Object]", causing an error when the page attempts to load. This issue rece ...

By default, showcase the value of the first item in the list selected in a mat-selection-list on a separate component

In my project, I have two essential components: 1)list (which displays a list of customers) 2)detail (which shows the details of a selected customer) These components are designed to be reusable and are being utilized within another component called cus ...

Utilizing combinedReducers will not prompt a re-render when dispatching actions

When I refrain from using combineReducers: const store = createStore<StoreState,any,any,any>(pointReducer, { points: 1, languageName: 'Points', }); function tick() { store.dispatch(gameTick()); requestAnimationFrame(tick) ...

Typescript fails to properly identify the yield keyword within a generator function or generator body

Here is the code for my generator function: function* generatorFunction(input: number[]): IterableIterator<number> { input.forEach((num) => { yield num; }); An error occurred during linting: A 'yield' expression is only allowed ...

What could be the reason for the discrepancy between my get_token() function and the value obtained from request.META.get("CSRF_COOKIE")?

Can anyone shed light on why I'm facing this particular issue? I am currently exploring the integration of Angular 17 as a Frontend with Django as a Backend. While validating a form, I encountered an issue where the token obtained from Django does no ...