Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  150] [ 3]  / answers: 1 / hits: 5456  / 3 Years ago, wed, april 7, 2021, 12:00:00

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


More From » typescript

 Answers
1

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[]);

[#1511] Saturday, April 3, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
;