Skip to content
Advertisement

Convert Maybe[]’ to ‘string[]

I am using graphql with generated types and struggling with how to convert them to the type I need to pass it to my data service calls.

@graphql-codegen has given me an args type of

export type QueryOrdersArgs = {
  ids: Array<Maybe<Scalars['ID']>>;
};

(I don’t really understand why its generated as a Maybe type, as the graphql schema enforces that I only query with a parameter of an array of ids (strings))

In my resolver, I need to call into a service which takes an array of strings. Everything works as expected (with @ts-ignore) but now I need to fix up my types.

const { orderIds } = args;
const result = getOrder(orderIds);

I have a codesandbox with just the types here https://codesandbox.io/s/typescript-playground-export-forked-3fpx9?file=/index.ts

export type Maybe<T> = T | null;
export type Scalars = {
  ID: string;
  String: string;
  Boolean: boolean;
  Int: number;
  Float: number;
  _FieldSet: any;
};

let ids: Array<Maybe<Scalars["ID"]>>;

export const getOrders = (orderIds: Array<string>) => {
  orderIds.map((x) => console.log(x));
};

getOrders(ids);

I currently get the error – “TS2345: Argument of type ‘Maybe[]’ is not assignable to parameter of type ‘string[]’.”

Any help greatly appreciated

Advertisement

Answer

If you’re confident that it shouldn’t be a Maybe type, you can cast it:

type Maybe<T> = T | null;
const maybeArray: Maybe<string>[] = [];
let stringArray: string[] = maybeArray as string[];

or in your case

getOrders(ids as string[]);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement