Encountering an issue: the argument with type '{ username: string; password: string; }' cannot be matched with the parameter of type 'RequiredEntityData<User>'

I have encountered an issue in my project where I keep getting a red underline at a specific line of code:

{
   username: options.username,
   password: hasedPassword
}

Upon hovering over it, the error message reads as follows:

Argument of type '{ username: string; password: string; }' is not assignable to parameter of type 'RequiredEntityData'. Type '{ username: string; password: string; }' is missing the following properties from type '{ createdAt: EntityDataItem; updatedAt: EntityDataItem; username: EntityDataItem; password: EntityDataItem; }': createdAt, updatedAtts(2345)

For reference, here is the complete file structure:

import { User } from "../entities/User";
import { MyContext } from "../types";
import { Arg, Ctx, Field, InputType, Mutation, Resolver } from "type-graphql";
import argon2 from 'argon2';

@InputType()
class UsernamePasswordInput {
    @Field()
    username: string

    @Field()
    password: string
}

@Resolver()
export class UserResolver {
    @Mutation(() => User) 
    async register(
        @Arg('options') options: UsernamePasswordInput,
        @Ctx() {em}: MyContext
    ) {
        const hasedPassword = await argon2.hash(options.password)
        const user = em.create(User, {
            username: options.username,
            password: hasedPassword
        })
        await em.persistAndFlush(user)
        return user
    }
}

Additionally, here's the content of package.json:

{
  "name": "practicegraphQL",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "watch": "tsc -w",
    "dev": "nodemon dist/index.js",
    "start": "ts-node src/index.ts",
    "create:migration": "mikro-orm migration:create"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.35",
    "nodemon": "^2.0.16",
    "ts-node": "^10.8.0",
    "typescript": "^4.6.4"
  },
  "dependencies": {
    "@mikro-orm/cli": "^5.1.4",
    "@mikro-orm/core": "^5.1.4",
    "@mikro-orm/migrations": "^5.1.4",
    "@mikro-orm/postgresql": "^5.1.4",
    "apollo-server-express": "^2.25.3",
    "argon2": "^0.28.5",
    "express": "^4.18.1",
    "graphql": "15.7.2",
    "pg": "^8.7.3",
    "reflect-metadata": "^0.1.13",
    "type-graphql": "^1.1.1"
  },
  "mikro-orm": {
    "useTsNode": true,
    "configPaths": [
      "./src/mikro-orm.config.ts",
      "./dist/mikro-orm.config.js"
    ]
  }
}

If you have any insights on how to resolve this error, your input would be greatly appreciated. Thank you!

As an update, I have included the User entity for reference:

@ObjectType()
@Entity()
export class User {

  @Field()
  @PrimaryKey()
  _id!: number;

  @Field(() => String)
  @Property()
  createdAt: Date = new Date();

  @Field(() => String)
  @Property({ onUpdate: () => new Date() })
  updatedAt: Date = new Date();

  @Field(() => String)
  @Property({unique: true})
  username!: string;
    
  @Property()
  password!: string;

}

Answer №1

When inside the @Resolver

    @Resolver()
export class UserResolver {
    @Mutation(() => User) 
    async register(
        @Arg('options') options: UsernamePasswordInput,
        @Ctx() {em}: MyContext
    ) {
        const hasedPassword = await argon2.hash(options.password)
        const user = em.create(User, {
            username: options.username,
            password: hasedPassword

            // include these lines inside
            createdAt: new Date,
            updatedAt: new Date
        })
        await em.persistAndFlush(user)
        return user
    }
}

Just remember to add

createdAt: new Date, updatedAt: new Date
within the
{username: options.username,password: hasedPassword}

in this manner

{username: options.username,password: hasedPassword, createdAt: new Date, updatedAt: new Date }
the text editor will not show an error.

Even though an error is displayed, your code will still function properly and you can insert rows into the database

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

Unexpected behavior: Promise.catch() fails to catch exception in AngularJS unit test

During the process of writing Jasmine unit tests for my Typescript app and running them via Resharper, I encountered an issue with executing an action when the handler throws an exception: describe("Q Service Test", () => { var q: ng.IQService; ...

Having difficulty displaying data in the proper format with two-way binding

In the realm of my webpage, I have a plethora of headings, paragraphs, images, and other data at my disposal. From the backend, a dataset is provided to me that includes an array with various properties housing the desired information. The challenge lies i ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

Is there a way to insert data from one table into a MySQL Table in Drizzle and update the entry if it already exists?

My goal is to utilize Drizzle for inserting data into a table and updating it if the key already exists. In MySQL, the code would look like this: INSERT INTO myTable1(field1,field2,field3,field4) SELECT fieldOne,fieldTwo,fieldThree,fieldFour FROM myTable2 ...

How can CSS and HTML be incorporated into Vue.js similarly to Angular, where CSS, HTML, and TypeScript are stored in separate files?

How can I include CSS and HTML files separately in Vue.js? I am new to Vue and currently learning Vue.js. One question that keeps popping up in my mind is how I can add CSS and HTML files separately, similar to how it's done in Angular. Thanks in adv ...

Express TypeScript Error Handling Function

What are the different data types for the four parameters used in the error handling function in Typescript? app.use((err: ??, req: ??, res: ??, next: ??) => { }); While working in VS Code, I noticed red wiggly lines under all four parameters without ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

Accept only the keys specifically assigned to an object

Trying to develop a TypeScript class where it is initialized with an object and contains a method that only accepts keys from that object. Here's the code: class MyClass { properties = {}; constructor(properties) { this.properties = propertie ...

The error in Angular 6 is that the property 'controls' is not available on the type 'AbstractControl'

What happens when we use setvalue in a for loop? Everything seems to be running smoothly, but unfortunately an error is thrown: The property 'controls' is not recognized on the type 'AbstractControl'. In Angular 6, how can we resol ...

Using Angular with Cordova - How to troubleshoot using TypeScript files?

Currently in the process of debugging the application using source files written in Typescript. Despite attempting to debug with Chrome, I have been limited to only being able to debug the Javascript files generated by Cordova which has proven difficult. ...

Having trouble retrieving an object property in HTML or TypeScript within an Angular framework?

export class ComponentOne { array_all_items: Array<{ page_details: any }> = []; array_page_details: Array<{ identifier: number, title: string }> = []; initial_item: Array<{ identifier: number, title: string }> = [ { ...

Adjust item size and move them into the panel

I am looking to create a panel that arranges items in a specific layout shown here: https://i.stack.imgur.com/qw3lS.png Below is the code I have attempted so far: import React, { useCallback, useEffect } from "react"; import { Box, Grid, Tab, T ...

Efficient methods to transfer values or arrays between components in Angular 8 without relying on local storage

I am working on a project that involves two components: a login component and a home component. I need to pass user data from the login component to the home component without using local storage. Is there a way to achieve this in Angular 8? Below is the ...

What is the best way to add an array object's property value to HTML?

I am attempting to build a basic carousel using DOM manipulation. I am not sure if it can be done in Angular, but my idea involves creating an array of objects with specific properties that I want to pass to the HTML through interpolation. However, I am ...

No call signatures found for TypeScript custom React hook

Trying out this new custom hook for API requests import { useState, useCallback } from 'react'; interface OptionsShape { method: 'GET' | 'POST'; } interface InitStateShape { data: any; success: boolean; loading: bool ...

Creating a new array by combining data from two arrays: a step-by-step guide

Here is an array I have: response=[ { "mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7", "title": "test2", "score": "4", "id": "91ce873f- ...

D3 version 4 with Typescript - How "this" is used in the context of d3.drag().on("end", this.dragended)

Currently, I am utilizing the D3 library for moving an element within a Venn diagram. Upon releasing the item after dragging, I aim to determine its position within the diagram. item.call(d3.drag() .on("start", this.dragstarted) .on("drag", this.d ...

Using TypeScript's Discriminated Union with an Optional Discriminant

After creating a discriminated union to type props in a React component, things got a bit interesting. Here's a simplified version of what was done: type Client = { kind?: 'client', fn: (updatedIds: string[]) => void }; type Serv ...

Generate detailed documentation for the functional tests conducted by Intern 4 with automated tools

I need to automatically generate documentation for my Intern 4 functional tests. I attempted using typedoc, which worked well when parsing my object page functions. However, it failed when working with functional test suites like the one below: /** * Thi ...