Type ‘A’ cannot be assigned to type ‘A | B | undefined’ in TypeScript

1 day ago 4
ARTICLE AD BOX

In a separate monorepo I have the type:

import {IExecutableSchemaDefinition} from "@graphql-tools/schema" export type ServerOptions<TContext> = { // This corresponds to // ‘IResolvers<any, MyContext> | Array<IResolvers<any, MyContext>> | undefined’ // from @graphql-tools/utils resolvers: IExecutableSchemaDefinition<TContext>["resolvers"] // other irrelevant types }

In another project I am doing the following:

import {IResolvers} from "@graphql-tools/utils" import {mergeResolvers} from "@graphql-tools/merge" import {ServerOptions} from "my-package" const mergedResolvers: IResolvers<any, MyContext> = mergeResolvers(myResolversList) const serverOptions: ServerOptions<MyContext> = { resolvers: mergedResolvers }

And I get an error under resolvers in serverOptions saying:

Type 'IResolvers<any, MyContext>' is not assignable to type 'IResolvers<any, MyContext> | IResolvers<any, MyContext>[] | undefined'. Type 'IResolvers<any, MyContext>' is missing the following properties from type 'IResolvers<any, MyContext>[]': length, pop, push, concat, and 35 more.ts(2322) ServerOptions.d.ts(10, 5): The expected type comes from property 'resolvers' which is declared here on type 'ServerOptions'

I cannot understand what is causing this issue because the type of my mergedResolvers is identical to the first type in the union type.

I can workaround this issue using casting (shown below), but I would like to understand and fix the underlying issue.

const mergedResolvers: ServerOptions<MyContext>['resolvers'] = mergeResolvers(myResolversList) as ServerOptions<MyContext>['resolvers']

The type definition of IResolvers beside mergedResolvers in my project, is located at:

node_modules > @graphql-tools > utils > typings > interfaces.d.ts

When I click on the ServerOptions link within the error, I get the following trail to IResolvers:

ServerOptions defined in:

user > dev > my-monorepo > packages > my-package > dist > types > src > common > types > ServerOptions.d.ts

IExecutableSchemaDefinition defined in:

user > dev > my-monorepo > node_modules > .pnpm > @[email protected][email protected] > node_modules > @graphql-tools > schema > typings > types.d.ts

IResolvers defined in:

user > dev > my-monorepo > node_modules > .pnpm > @[email protected][email protected] > node_modules > @graphql-tools > utils > typings > interfaces.d.ts

And the type definitions for IResolvers in two files are identical (whether from the @graphql-tools/utils directly in my project, or by going through the ServerOptions trail to the type definition of IResolvers).

Any explanation for this would be greatly appreciated.

Read Entire Article