I don't understand why TypeScript is throwing an error even though my conditionals perfectly match the specified types

Encountering an Error When Defining Types as an Array of createdEvents in TypeScript

When trying to define the types as an array of createdEvents or string, I am facing the following error:

Type '(parent: User, args: InputShapeFromFields<InputFieldMap<"InputObject" | "Arg">>, context: { currentUser: User; }) => "No events created" | (string | createdEvents[])[]' is not assignable to type 'Resolver<User, InputShapeFromFields<InputFieldMap<"InputObject" | "Arg">>, { currentUser: User; }, createdEvents[] | null | undefined, "No events created" | (string | createdEvents[])[]>'. Type '"No events created" | (string | createdEvents[])[]' is not assignable to type 'MaybePromise<readonly MaybePromise[]> | null | undefined'. Type '"No events created"' is not assignable to type 'MaybePromise<readonly MaybePromise[]> | null | undefined'.

The error seems to indicate that the field I am creating is not compatible with the User type.

I have attempted the following:

  1. Returning parent.createdEvents alone
  2. If it's undefined, return null, undefined, and an empty array

However, none of these solutions work. Interestingly, adding "any" as an option for the user createdEvents type definition resolves the issue as shown below:

export class User {
    _id: ObjectId;
    name: string;
    email: string;
    password?: string;
    availableWeights?: number[];
    createdEvents?: createdEvents[] | string;
    signedUpEvents?: userSignUp[];

    constructor(id: ObjectId, name: string, email: string, password?: string, availableWeights?: number[],
        createdEvents?: createdEvents[] | string, signedUpEvents?: userSignUp[]) {
        this._id = id;
        this.name = name;
        this.email = email;
        this.password = password;
        this.availableWeights = availableWeights;
        this.createdEvents = createdEvents;
        this.signedUpEvents = signedUpEvents;
    }
}

By appending "| any" to the end of the createdEvents field, the error disappears.

Error Encountered in Resolve Function:

 createdEvents: t.field({
            type: [createdEvents],
            resolve: (parent, args, context) => {
                if (parent.createdEvents == undefined || parent.createdEvents == null || parent.createdEvents.length == 0) {
                    return "No events created";
                } else {
                    return parent.createdEvents;
                }
            }
        }),

Below is the Class Definition Used Throughout the Code:

export class createdEvents {
    _id: ObjectId;
    eventName: string;
    eventDate: Date;
    eventDescription: string;
    cost?: string;
    eventLink?: string;
    weights?: weightsForUserCreatedEvents[];

    constructor(_id: ObjectId, eventName: string, eventDate: Date, eventDescription: string, cost?: string, eventLink?: string, weights?: weightsForUserCreatedEvents[]) {
        this._id = _id;
        this.eventName = eventName;
        this.eventDate = eventDate;
        this.eventDescription = eventDescription;
        this.cost = cost;
        this.eventLink = eventLink;
        this.weights = weights;
    }
}

Answer №1

Solution Provided by Michel Floyd

Replace the string with undefined

export class User {
    _id: ObjectId;
    name: string;
    email: string;
    password?: string;
    availableWeights?: number[];
    createdEvents?: createdEvents[] | undefined;
    signedUpEvents?: userSignUp[];

    constructor(id: ObjectId, name: string, email: string, password?: string, availableWeights?: number[],
        createdEvents?: createdEvents[] | undefined, signedUpEvents?: userSignUp[]) {
        this._id = id;
        this.name = name;
        this.email = email;
        this.password = password;
        this.availableWeights = availableWeights;
        this.createdEvents = createdEvents;
        this.signedUpEvents = signedUpEvents;
    }
}
        createdEvents: t.field({
            type: [createdEvents],
            resolve: (parent, args, context) => {
                if (parent.createdEvents == undefined || parent.createdEvents == null || parent.createdEvents.length == 0) {
                    return undefined;
                } else {
                    return parent.createdEvents;
                }
            }
        }),

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

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

Looking to achieve a scroll effect with mix-blend-mode using JavaScript?

I am seeking a method to adjust the background color of a specific element based on the background itself. While CSS offers the mix-blend-mode property, I am looking to specify the color manually. Ideally, I would like to achieve the same effect using an ...

"Utilizing Express's Jade middleware to efficiently handle and manage

Can you create a custom exception handler for errors in jade templates? For example: // server.js app = express(); app.set('view engine', jade); app.locals.js = function () { throw new Error('hello'); } // views/index.jade html != ...

Navigate through stunning visuals using Bokeh Slider with Python callback functionality

After being inspired by this particular example from the Bokeh gallery, I decided to try implementing a slider to navigate through a vast amount of collected data, essentially creating a time-lapse of biological data. Instead of opting for a custom JavaS ...

Are you looking to enhance your website with dynamic and

I am looking to display dynamic text in a label using HTML. This label should be populated with text from a Javascript function upon loading or reloading the page. How can I make this happen? <label id="MyLabel"></label> <script type="tex ...

Learn how to efficiently execute a function multiple times using pure JavaScript

I am trying to create a tabbed content functionality with multiple elements. How can I utilize the same function for various elements declared in a variable? For example, I want to clone the parent div.tabs element with similar content but different ids an ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

The index access result is not inferred when intersecting a Record with a generic key that extends a template literal

Essentially, (T & Record<K, U>)[K] should result in U, but it encounters issues when K is generic and extends a template literal. function foo3< K extends `a${string}`, >(k: K) { const a = {} as {b: 1} & Record<K, string> ...

Dynamically adding items in a row to a form panel using extjs

While using ExtJS 3.4, I faced a challenge with laying out three buttons in a row within a formpanel. After some research, I discovered that nesting item blocks might be the correct approach. Below is the code snippet showcasing what I have implemented: v ...

Find two separate solutions to the promise

I'm in the process of developing a promise-based route and here is my current promise implementation: const allowEdit = (postid, username) => { return new Promise((resolve) => { db.query(`SELECT * FROM post WHERE id = ${postid} AND usernam ...

Calculating totals based on user input using an array as a variable in JavaScript

I am looking to store the total for a specific database object with the id of 3. There are various ids with different values, but in this instance, I am focusing on storing the value of 2. In addition to storing the value, I also want to be able to increm ...

Reconstructing a file from a string using the FileReader in reverse

Converting the file to a string: const reader = new FileReader() reader.readAsText(file, 'UTF-8') reader.onload = (event) => { this.textFile = event.target.result }; Upon uploading a Zip, Text, or Image file, my string appears as: data:t ...

Using Vue.js to create numerous modal popups

Currently, I am using Vue.JS for a research project at my workplace. My focus right now is mainly on the front-end. I have a table with several entries, and when a row is clicked, I want a modal popup window to display further details about that specific ...

TRPC fails to respond to the passed configuration or variables (e.g., when enabled is set to false)

Recently started using trpc and I'm trying to grasp how to utilize useQuery (which I've previously worked with in react-query): const IndexPage = () => { const { isLoading, data, isIdle } = trpc.useQuery([ "subscriber.add", { email: ...

Using Protractor to extract text from multiple paragraphs

How do I retrieve the values of all paragraphs (p) at once? Below is an example of how my inspect view appears: "Testing sample one." "Testing sample two." And here is a snippet of my code to extract the value of id 'run': browser.findElement ...

Retrieve JSON information using PHP and JavaScript SDK exclusivley

After successfully setting up the Facebook Javascript SDK and getting it to display the right information on the page, I have also managed to echo the user into the Firebug console to show the Object containing all of the user profile details. * I am opti ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

Unable to add ngRoute dependency in Angular

I'm facing an issue while trying to set up a basic Angular route in my current project, encountering the error: Uncaught Error: [$injector:modulerr] I have ensured that I have injected ngRoute as a dependency in my module and included the angular-rou ...

Organize, filter, and compare an array of objects using a specific format

Organize my JSON data in the following format: [{"x":"Jan-2017","y":41},{"x":"Feb-2017","y":20},{"x":"Mar-2017","y":45},{"x":"Apr-2017","y":29},{"x":"May-2017","y":59},{"x":"Jun-2017","y":378},{"x":"Jul-2017","y":354},{"x":"Aug-2017","y":398},{"x":"Se ...

Get the application/pdf document that was just sent to you from the software backend

I am facing an issue with downloading a PDF file sent from the backend. Upon receiving a blob response, I notice that when I download and view the file, the sheets are empty, matching the expected number of sheets. Could this be a coding problem? Current ...