Resolving the "Abstract type N must be an Object type at runtime" error in GraphQL Server Union Types

Given a unique GraphQL union return type:

union GetUserProfileOrDatabaseInfo = UserProfile | DatabaseInfo

meant to be returned by a specific resolver:

type Query {
  getUserData: GetUserProfileOrDatabaseInfo!
}

I am encountering warnings and errors related to the __resolveType or __isTypeOf function:

The abstract type M must resolve to an Object type at runtime for field Query.getUserData with value { ..., __isTypeOf: [function __isTypeOf] }, received "undefined". Either the M type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.'

After extensive research on GitHub issues and Stack Overflow questions, I have yet to find a solution to fix this error.

Implementing __resolveType or __isTypeOf in my resolvers has been unsuccessful:

export const Query = {
  getUserData: (parent, args, context: IContext, info) => {
    return {
      __isTypeOf(obj) { // OR __resolveType, none of them work
        return `UserProfile`;
      },
      data: []
    };
  },
};

Answer №1

After struggling with implementing __resolveType or __isTypeOf in my resolvers, I finally found a solution by directly adding the __typename into the resolver return Object to resolve the issue.

In the implementation of the getBankAccounts resolver:

async getBankAccounts(): GetBankAccountsResponseOrUserInputRequest {
    if (shouldGetUserInputRequest()) {
      return {
        __typename: "UserInputRequest",
        ...response,
      };
    }

    return {
      __typename: "GetAccountsResponse",
      accounts,
    };
  }

I hope this solution can be useful for someone facing a similar challenge.

Answer №2

Your resolver map is not configured correctly.

When passing the resolver map to ApolloServer (or makeExecutableSchema), it should be an object with keys representing type names in your schema. Each key should map to another object with field names on that type, each mapping to a resolver function.

const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
  },
}

The same resolver map is used for providing the resolveType function for unions or interfaces. The structure remains similar, but the key becomes __resolveType and corresponds to the union or interface's name:

const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
  },
  SomeUnion: {
    __resolveType: (parent) => { ... },
  }
}

The resolveType function must return a string matching an existing object type in your schema.

If you opt for __isTypeOf over __resolveType, note that isTypeOf is specific to an object type and not the interface or union itself. Refer to the docs for clarity. In this case, the resolver map looks like:

const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
    __isTypeOf: (parent) => { ... },
  },
}

__isTypeOf should always return either true or false, confirming if the passed object matches the type.

Choose between __resolveType or __isTypeOf; using the latter requires adding it to every possible object type in the union or interface.

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

Issues arise with the escape key functionality when attempting to close an Angular modal

I have a component called Escrituracao that handles a client's billing information. It utilizes a mat-table to display all the necessary data. When creating a new bill, a modal window, known as CadastrarLancamentoComponent, is opened: openModalLancame ...

Guide on formatting the API response using a callback function in Angular development

How can I reformat my API response using a callback function and access the data within the angular subscribe method? I attempted to use mergemap but it didn't work as expected. this.http.get('https://some.com/questions.xml', {headers, res ...

Passing a reference to a react functional component (react.FC) results in a type error: The property ref is not recognized on the type 'IntrinsicAttributes & Props & { children: ReactNode}'

Currently, I am working on mastering the utilization of forward refs. In a functional component (FC), I am trying to initialize all my refs and then pass them down to its child components so that I can access the canvas instances of some chartjs charts. Ho ...

Enable the use of unfamiliar techniques on object

I am facing a challenge with an object that contains multiple method names which are not known at compile time. The signature of these methods always remains the same, but I am unsure about how to handle this scenario. I attempted to utilize an index type ...

Tips for showcasing an array's values as a list of comma-separated values

31: (2) ["https://localhost:44375/api/Image/2388", "https://localhost:44375/api/Image/2388"] The value is currently being displayed in this format, but I would like it to be shown as: https://localhost:44375/api/Image/2388, https://localhost:44375/api/Im ...

What could be the reason for ngOnChanges lifecycle hook not getting invoked?

I am currently experimenting with Angular 2 in an effort to learn more about it. I noticed that ngOnChanges is not triggering in the code below: app.component.ts: import { Component, Input } from "@angular/core" import { FormsModule } from '@angular ...

Error in React Router when using TypeScript

Encountering errors while trying to set up router with React and TypeScript. https://i.sstatic.net/muSZU.png I have already attempted to install npm install @types/history However, the issue persists. Your assistance would be greatly appreciated. Thank y ...

A guide to implementing localStorage in TypeScript

When attempting to assign the object item to Product using this code: localStorage.setItem("Product", JSON.stringify(item)) The JSON string of item is not properly assigned to Product. Is there a solution to this issue? ...

Can someone please explain how to bring in the Sidebar component?

click here for image description check out this image info An issue arises as the module '@components/Sidebar' or its type declarations cannot be located.ts(2307) Various attempts were made, including: import Sidebar from '@components/Sid ...

What are some ways to resolve this console error: "TS2307: Could not locate module '@components/common/ButtonBlock' or its corresponding type declarations."

While the project is running smoothly, I am noticing a multitude of errors appearing in the console of VS Code. How can I eliminate these error messages? It seems to be related to TypeScript. Additionally, I am encountering an error in the browser as well ...

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

Accessing information from an Odata controller in Angular2

Greetings as a first-time question asker and long-time reader/lurker. I've been delving into learning angular2, but I'm facing some challenges when it comes to retrieving data from an odata controller. In my simple Angular 2 application, I'm ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

The Challenge of Iterating Through an Array of Objects in Angular Components using TypeScript

Could someone please explain why I am unable to iterate through this array? Initially, everything seems to be working fine in the ngOnInit. I have an array that is successfully displayed in the template. However, when checking in ngAfterViewInit, the conso ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

What is the ideal configuration for Typescript within ASP.NET 4 MVC 5 on Visual Studio 2015?

Currently, I am in the process of integrating a TypeScript project into a VS2015 MVC 5 project (which is based on ASP.NET 4, specifically not asp.net 5 or asp.net 6 - only the MVC portion is version 5). All aspects of my query pertain solely to this target ...

Upon running the code, no errors appear on the console. However, my project isn't functioning properly and I'm encountering errors on the web console

ReferenceError: require is not defined when trying to access external "url" at Object.url in webpack_require (bootstrap:83) at client:6 importing from webpack-dev-server client index.js(http://0.0.0.0:0) vendor.js:219506 dynamically imp ...

Resolving the Challenge of Disabling typescript-eslint/typedef in Angular 13 with ESlint

I started a fresh project in Angular 13 and configured typescript-eslint by running the command below: ng add @angular-eslint/schematic I made changes to my .eslintrc.json file where I disabled the rules for "typescript-eslint/typedef" and "typescript-esl ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...