Issue TS2351: It appears that this particular expression is not capable of being constructed. (Utilizing AJV in a

Currently, I am encountering an issue while trying to use AJV with Typescript. I previously raised a similar concern in the ajv repository but unfortunately did not find a solution.

The problem arises when attempting to import the Ajv module as follows:

import Ajv from "ajv;

I aim to utilize it in the same manner as I would in plain JavaScript.

 const ajv = new Ajv({ allErrors: true });

However, the TypeScript compiler is flagging an error like this:

error TS2351: This expression is not constructable.
  Type 'typeof import("/Users/username/Documents/node_modules/ajv/dist/ajv")' has no construct signatures.

 const ajv = new Ajv({ allErrors: true });

Could it be that I am making a mistake during the import procedure?

This is what my TS configuration file looks like:

 `{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */

    /* Language and Environment */
    "target": "ES6",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    /* Modules */
    "module": "Node16",                                /* Specify what module code is generated. */
    "moduleResolution": "Node16",                          /* Specify how TypeScript looks up a file from a given module specifier. */

    /* JavaScript Support */

    /* Emit */
    "outDir": "./dist",                                  /* Specify an output folder for all emitted files. */

    /* Interop Constraints */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true,                                 /* Skip type checking all .d.ts files. */

    "sourceMap": true,
    "rootDir": "src",
    "declaration": true,
    "types": ["node", "mocha"]
  },
  "include": ["src/**/*", ".env"],
  "exclude": ["dist/**/*", "node_modules", "test/**/*"]
}
` 
 

Your assistance on this matter would be highly appreciated. Thank you very much....

I was under the impression that there should be no errors from the TS compiler since I compile JS files during the deployment process.

Answer №1

If you're encountering issues with CommonJS versus ES Modules, here's a solution to consider.

To fix the import error, adjust your code as shown below:

import _Ajv from "ajv";

const Ajv = _Ajv as unknown as typeof _Ajv.default;

After making this change, you should be able to instantiate the object successfully:

const ajv = new Ajv();

For more details and context, you can refer to the discussion at: https://github.com/ajv-validator/ajv/issues/2132#issuecomment-1290409907

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

Changing the cursor while the onDrag event is active in ReactJs

I want to implement Drag functionality on certain elements in my application, but I am facing an issue where the cursor changes during dragging. How can I change the cursor specifically when onDrag is active? ...

Do not proceed with the form submission if the fields are left blank

I am facing a challenge with organizing two sets of data, "heat" and "cold", obtained from an external provider. The data is messy and I have trimmed down the code to focus on the main issue at hand. Both "heat" and "cold" have properties that users need t ...

Different ways to modify the color and thickness of a variable in HTML5 with either JavaScript or CSS

I am currently working with a JavaScript file where I have a variable defined as follows: var nombre = document.getElementById('nombre').value; The 'nombre' variable corresponds to an element in an HTML file: Nombre: <input type=" ...

Sending a form from an iPhone device to a PHP backend server

It seems like I'm overlooking a simple aspect... Here is a basic form that I want to submit to a PHP script. It works perfectly on PC and Mac, but it doesn't function properly in Safari on iPad, iPhone, etc. Do you think there's some mobile ...

"Troubleshooting: Why is my AngularJS ng-click not triggering the function

My custom directive fetches a navigation block from a webservice call. I am attempting to click on a navigation link that has an "ng-click" attribute set, which should call the specified function. However, the function is not being executed. Below is my r ...

The result shows me [object Object]

I'm struggling to find the solution to my issue - the output I am getting is incorrect and I can't pinpoint what's wrong. It's possible that some part of the code is missing, but as a learner, I'm not entirely sure. My goal is to ...

"Troubleshooting a CSS problem with off-canvas layouts

I've created a page with divs that create a parallax effect on scrolling, you can view the demo here. However, I encountered an issue when adding a Foundations off-canvas menu - it prevents me from being able to scroll down. How can I resolve this an ...

Retrieving JSON information from the node's request

Recently, I launched a new website using a node server to delve deeper into the world of node.js. I've been sending data to the server, but I'm struggling to decode the JSON data in the request: Here is an example of a client request: function ...

Issue with package: Unable to locate the module specified as './artifacts/index.win32-ia32-msvc.node'

I am encountering an issue while using Parcel for the first time. When I execute npx parcel .\app\index.html, I receive the following error: Error: Module not found './artifacts/index.win32-ia32-msvc.node' Require stack: - C:\Users ...

What is the best method for fetching the values of a select element in React.js?

I'm struggling to retrieve the value of a selected element in a dropdown list. I've tried debugging it, but haven't been able to get the value. I attempted to console log e.target.value, but unfortunately, it didn't work. Any thoughts o ...

Include in assortment if not already in stock

I have a document embedded within my collection labeled as likes: { "_id" : ObjectId("57a31e18fa0299542ab8dd80"), "created" : ISODate("2016-08-04T10:51:04.971Z"), "likes" : [ { "user" : ObjectId("1"), "date" : ...

I am facing a challenge in retrieving the chosen item from a drop-down menu on my subsequent page using AngularJS

Here is the code snippet from my app.js file: var countryApp = angular.module('countryApp', ['ngRoute']); countryApp.controller('testController', ['$scope', '$http', '$location', function ($scope ...

Creating an HTML table with two arrays displayed and a delete button for confirming deletion

I have created a function to populate two arrays with movie information and display it in a table on the screen. However, I am struggling to make the delete button appear and to separate the titles and directors into different columns. How can I achieve ...

Tips for toggling the visibility of an element when a button is clicked in React

In my todo list, I need to display the details of each item when clicked on a button. There are two buttons available: "View Details" and "Hide Details". Below is the code snippet: class Todos extends React.Component{ construc ...

Adjustment in orientation compared to the position of the head-mounted display

At the moment, I am utilizing a system where the camera in the world moves based on the change in position from the hmd. The problem arises when I turn to face the positive x-axis and move forward - only the x-axis changes, making it impossible to walk for ...

The Threejs Raycaster detects collisions with objects even when the ray is just grazing the surface

Within my Vue component, I have integrated a threejs scene and I am facing an issue with selecting objects using the mouse. I am currently using the OnPointerDown event and raycaster to locate objects under the mouse pointer. However, it seems like the ray ...

Determine if two instances are within the same week, where each week starts on Friday and ends on Thursday, using moment.js

Currently, I'm in the process of developing a Discord bot using node.js and discord.js. One of the features allows users to vote through a command, but I want to restrict them to voting only once per week. The challenge lies in the fact that in this ...

A checkbox placed within an anchor tag

Here is some code that I have: <a href class="dropdown-toggle"> <input type="checkbox" ng-model="test.checked"> <span class="fa fa-angle-down"></span> </a> When I click on the above code, I want the chec ...

Using JQuery to create animations with fadeIn and fadeOut effects is a great way to

As a complete newbie taking my first steps in front-end development, I spent most of my day trying to work out an animation function but couldn't quite get it right. Below are the snippets of HTML, CSS, and JavaScript codes: <!DOCTYPE html> < ...

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...