简体   繁体   English

转换可能<string> []' 到 '字符串[]</string>

[英]Convert Maybe<string>[]' 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 与生成的类型一起使用,并努力解决如何将它们转换为我需要将其传递给我的数据服务调用的类型。

@graphql-codegen has given me an args type of @graphql-codegen 给了我一个 args 类型的

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)) (我真的不明白为什么它生成为 Maybe 类型,因为 graphql 模式强制我只使用 ids(字符串)数组的参数进行查询)

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.一切都按预期工作(使用@ts-ignore)但现在我需要修复我的类型。

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我有一个只有类型的codesandbox 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[]'."我目前收到错误 - “TS2345:'Maybe[]' 类型的参数不可分配给'string[]' 类型的参数。”

Any help greatly appreciated非常感谢任何帮助

If you're confident that it shouldn't be a Maybe type, you can cast it:如果你确信它应该是 Maybe 类型,你可以强制转换它:

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

or in your case或者在你的情况下

getOrders(ids as string[]);

To remove Maybe , you need to filter non nullable items要删除Maybe ,您需要过滤不可为空的项目

const nonNullable = <T>(value: T): value is NonNullable<T> =>
  value !== null && value !== undefined

getOrders(ids.filter(nonNullable));

But if you want to remove the Maybe from your schema, you need to an exclamation mark !但是如果你想从你的模式中删除Maybe ,你需要一个感叹号! in the graphql schema to be a required field在 graphql 模式中成为必填字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM