Issue encountered in NestJS with Prisma: When trying to invoke the class constructor t without using 'new', an error occurs stating that it

I've been attempting to establish a Prisma client within my NestJS application, but I keep encountering this persistent error:

[Nest] 14352  - 12.05.2023, 23:21:13   ERROR [ExceptionHandler] Class constructor t cannot be invoked without 'new'

TypeError: Class constructor t cannot be invoked without 'new'                                                     
    at new PrismaService (C:\work\js\cyno-desu\dist\prisma\prisma.service.js:66:42)                                
    at Injector.instantiateClass (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:351:19)
    at callback (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:56:45)
    at Injector.resolveConstructorParams (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:136:24)
    at Injector.loadInstance (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:61:13)
    at Injector.loadProvider (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:88:9)
    at Injector.lookupComponentInImports (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:281:17)
    at Injector.lookupComponentInParentModules (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:245:33)
    at Injector.resolveComponentInstance (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:200:33)
    at resolveParam (C:\work\js\cyno-desu\node_modules\@nestjs\core\injector\injector.js:120:38)

The code that's triggering the error looks like this:

    import { Injectable, OnModuleInit, INestApplication } from '@nestjs/common';
    import { PrismaClient } from '@prisma/client';
    
    @Injectable()
    export class PrismaService extends PrismaClient implements OnModuleInit {
      async onModuleInit() {
        await this.$connect();
      }
    
      async enableShutdownHooks(app: INestApplication) {
        this.$on('beforeExit', async () => {
          await app.close();
        });
      }
    }

This is a list of dependencies being used:

  "devDependencies": {
    "@nestjs/cli": "^9.0.0",
    "@nestjs/schematics": "^9.0.0",
    "@nestjs/testing": "^9.0.0",
    "@types/express": "^4.17.13",
    "@types/jest": "29.5.0",
    "@types/node": "18.15.11",
    "@types/supertest": "^2.0.11",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "@typescript-eslint/parser": "^5.0.0",
    "eslint": "^8.0.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "jest": "29.5.0",
    "prettier": "^2.3.2",
    "prisma": "^4.13.0",
    "source-map-support": "^0.5.20",
    "supertest": "^6.1.3",
    "ts-jest": "29.0.5",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "4.2.0",
    "typescript": "^4.7.4"
  },

I've attempted implementing the `new` keyword in various places, but it seems like there may be an issue with dependency injection within NestJS itself. Despite this being a seemingly straightforward example, I'm surprised nobody has identified the bug yet. My background lies in Java programming, where objectivity reigns supreme, so navigating this problem has proven more challenging than expected.

Answer №1

Read more about TypeScript Class Constructor Error here

Troubleshooting the 'Class constructor cannot be invoked without "new"' Issue in TypeScript

If you're encountering the dreaded "Class constructor cannot be invoked without new" error in TypeScript, it could be due to your tsconfig.json file's target property being set lower than es6 or improperly instantiating a class without the necessary new operator.

To fix this issue, make sure to update the target property in your tsconfig.json file to at least es6 and ensure that you correctly use the new operator when creating instances of classes.

Start by revisiting your tsconfig.json file and confirm that the target setting is specified as es6 or a newer version.

Your target setting dictates the JavaScript language version used in the output files. It's crucial to select es6 or above since modern browsers and Node.js fully support ES6 features. Opting for a lower target version like es5 would require TypeScript to transpile classes into functions, potentially leading to errors.

If your error stems from this configuration mismatch, switching the target to es6 should address it effectively.

Don't forget to restart both your code editor and development server if the problem persists.

Here's a snippet from my own tsconfig.build.json illustrating how to rectify the issue:

{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts"],
  "compilerOptions": {
   
    //THIS!@
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": "./",
    "paths": {
      "*": ["src/*"]
    },
    "endOfLine": "crlf" // set endOfLine to "crlf" for Windows CRLF
  }
}

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

Node.js has been giving me trouble as I try to install Inquirer

:***Hey Guys I'm Working on a TypeScript/JavaScript Calculator! ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...

Unable to set dimensions for an image within an input field using TypeScript

My goal is to retrieve and assign the height and width of an image to hidden text inputs in HTML, as shown below: The purpose is to obtain the height and width for validation. HTML: <input type="file" class="file" #introIcon id="uploadBtn" (change)=" ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Having trouble getting the onClick function to work in your Next.js/React component?

Recently, I delved into using next-auth for the first time and encountered an issue where my login and logout buttons' onClick functions stopped working when I resumed work on my project the next day. Strangely, nothing is being logged to the console. ...

How to properly convert JSON into a string within a nested object

Below is the JSON that I am passing and its result when logged in the console: boundary: Array(1) 0: points: Array(98) 0: {x: 117.5, y: 99} 1: Point {x: 116.5, y: 100} 2: Point {x: 116.5, y: 103} 3: Point {x: 114.5, y: 109} 4: Point {x: 113.5, y: 116} 5: P ...

TypeScript: "Implementing" methods. The organized approach

Currently, I am developing a middleware class for Express. Before delving into the details of the class, it's important to note that I will be injecting the middleware later by creating an instance of my "Authenticator" class and then using its method ...

Troubleshooting internet connectivity issues with Ionic 2

I am attempting to troubleshoot my internet connection. I have written the following code but it does not seem to be returning any results for me. ionViewDidEnter() { this.network.onConnect().subscribe(data => { console.log(data) }, error =&g ...

React array fails to update upon modification

Hey there! I've created a component that takes an array of strings, combines them, and then renders a typing animation by wrapping each character in a span tag with toggling opacity from 0 to 1. I noticed an issue when switching the order of displaye ...

Converting Objects to Arrays with Angular Observables

After searching extensively on SO for answers regarding item conversions in Javascript/Angular, I couldn't find a solution that addresses my specific problem. When retrieving data from Firestore as an object with potential duplicates, I need to perfor ...

Issue with Displaying Local Server Image in Angular 2 HTML

I am facing an issue with my Angular 2 Application. It retrieves items from a local database where the server stores the image of the item and the database stores the path to that image stored on the server. While I can retrieve all the items without any p ...

Troubleshooting Node TypeScript with Visual Studio Code using webpack bundling

(In a similar context to this query, but more focused on VsCode) I am attempting to debug the AngularU starter kit with Visual Studio Code. However, it is combining the TypeScript output into one bundle.js along with a side bundle.js.map: ↳web ↳dis ...

Please convert the code to async/await format and modify the output structure as specified

const getWorkoutPlan = async (plan) => { let workoutPlan = {}; for (let day in plan) { workoutPlan[day] = await Promise.all( Object.keys(plan[day]).map(async (muscle) => { const query = format("select * from %I where id in (%L) ...

What is the process of adding an m4v video to a create-next-app using typescript?

I encountered an issue with the following error: ./components/Hero.tsx:2:0 Module not found: Can't resolve '../media/HeroVideo1-Red-Compressed.m4v' 1 | import React, { useState } from 'react'; > 2 | import Video from '../ ...

What strategies can I use to prevent the need to create new instances of my service and repository for every

Currently, I am delving into the world of JavaScript using the Express.js Framework. My current learning project involves creating a simple restaurant application to grasp the ins and outs of CRUD operations related to ingredients. I have meticulously craf ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

What is the best way to display converted value in Angular 8?

In my current project, I am utilizing .NET Core 2.2 for the backend and Angular 8 for the frontend. The scenario involves having integer values on the backend within a specified range. For example: [Required] [Range(1073741824, 1099511627776)] // ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Basic Karma setup with Typescript - Error: x is undefined

I am trying to configure a basic test runner using Karma in order to test a TypeScript class. However, when I attempt to run the tests with karma start, I encounter an error stating that ReferenceError: Calculator is not defined. It seems like either the ...