Resolving conflicts between TypeGraphQL and Prisma 2 types

Currently, my development stack consists of TypeGraphql, Prisma 2, an Apollo Express server, and a PostgreSQL database.

To facilitate the generation of TypeScript types, I utilized Prisma to introspect my database and generate types from the schema.prisma file.

Additionally, I have defined my @ObjectType model classes using TypeGraphQL.

However, I am encountering type conflicts between my TypeGraphQL classes and the Prisma-generated types. For instance, I have a TypeGraphQL class named Course structured as follows:

@ObjectType()
export class Course {
  @Field(() => Int)
  id: number;

  @Field()
  title: string;
  .......

  @Field(() => User)
  creator: User;
}

On the other hand, Prisma generates a type for Course that looks like this:

/**
 * Model Course
 */

export type Course = {
  id: number
  title: string
  .......
  creator_id: number
}

When attempting to create a Course in my custom resolvers, I encounter a discrepancy in the types. The mismatch is causing TypeScript to flag an error indicating that the creator is missing in one Course type but required in another. This inconsistency has left me uncertain about the optimal resolution approach.

Is there a method to effectively merge my TypeGraphQL classes with the Prisma types or pursue an alternative strategy?

Answer №1

When you bring in the types, consider using the as keyword (also known as a type assertion) to give a different name to one of the types. For instance, you can rename the Course from Prisma to PrismaCourse, DBCourse, CourseModel, or any other preferred name. Here's how you can do that:

import { Course as DBCourse } from '@prisma/client'

Subsequently, in your resolver, you can include the following code:

export const createCourseService = async (
  prisma: PrismaClient,
  createCourseInput: CreateCourseInput,
  userId: number
): Promise<DBCourse> => {
  let err, newCourse, foundUser;
  const { course, user } = prisma;

  .....

  [err, newCourse] = await to(
    course.create({
      data: {
        ...createCourseInput,
        creator: {
          connect: { id: userId },
        },
      },
    })
  );
  return newCourse;
};

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

Errors TS2585 and TS2304 encountered during compilation of TypeScript file using Axios

What steps should I take to fix the errors that arise when attempting to compile my TypeScript code using tsc index.ts? node_modules/axios/index.d.ts:75:3 - error TS1165: In an ambient context, a computed property name must reference an expression of lite ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element ...

Encountered an error stating "Cannot find module node:fs" while using eslint-typescript-import, eslint-import-resolver-typescript,

Challenge My attempt to configure path alias in my TypeScript project was met with failure. Two errors arose during the execution of npm start: Module not found: Error: Can't resolve '~/App' in 'D:\work\workbench\templa ...

What is the functionality of angular-cli@webpack?

After working with angular-cli using systemJS, I have become comfortable with the build process, test cases, and component interaction. Recently, I made the switch from angular-cli to angular-cli@webpack. However, I am now facing confusion on a few point ...

Limit the types of function parameters to only one option within a union type parameter

I have a collection of tuples that I can use to define variables: type KnownPair = ["dog", "paws"] | ["fish", "scales"]; const goodPair: KnownPair = ["dog", "paws"]; //@ts-expect-error you cannot mix them: const badPair: KnownPair = ["dog", "scales"]; I ...

Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature. Initially, my HTML template looked like t ...

I am interested in showcasing a distinct screen layout specifically designed for mobile device viewing

Looking to display different screens for PC and smartphone users. I am using react, Typescript, and next.js for development. Specifically, I need to show user.tsx when accessing the /user URL from a PC, and Accessdenied.tsx when accessing it from a smartp ...

Guide on accomplishing masking in Angular 5

I'm curious if it's achievable to design a mask in Angular 5 that appears as follows: XXX-XX-1234 Moreover, when the user interacts with the text box by clicking on it, the format should transform into: 1234121234 Appreciate your help! ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

An object resulting from the combination of two separate objects

After reading a helpful solution on StackOverflow about merging properties of JavaScript objects dynamically, I learned how to utilize the spread operator in Typescript. However, one question still remains unanswered - what will be the type of the object c ...

Easiest Angular Carousel Solution

My goal is to create a basic Angular Carousel to enhance my understanding of Angular. While I have received helpful answers in the past, I am seeking further clarification to deepen my knowledge of Angular2+ and Typescript. Here's what I have so far: ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

Experiencing unfamiliar typescript glitches while attempting to compile a turborepo initiative

I have been utilizing the turborepo-template for my project. Initially, everything was running smoothly until TypeScript suddenly started displaying peculiar errors. ../../packages/fork-me/src/client/star-me/star-me.tsx:19:4 nextjs-example:build: Type erro ...

What is the best way to determine if a child component's property has changed within a method?

The child component is app-google-maps-panel and has 2 properties in the parent component: <div class="col-6"> <app-google-maps-panel [longitude]="longitude" [latitude]="latitude"></app-google-maps-panel> & ...

Deactivate the button while the form is being submitted

I need a way to prevent users from clicking the submit button multiple times while the form is being processed by the server. Below is the solution I have come up with: clear() { this.count++ this.formGroup.get('name').reset(null); ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Importing TypeScript enums into a Vue or browser context can lead to errors or the need for additional dependencies

I'm encountering a problem when trying to import type definitions from a separate module in my Vue project. Below is the structure of the typedefs I am attempting to import: import { Server, createServer } from "net"; export namespace Testable { ...

In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together. HTML CODE : <input type="tex ...