我对生成的类型使用graphql,并且很难将它们转换为我需要将其传递给数据服务调用的类型。
@graphql-codegen给了我一种args类型的
export type QueryOrdersArgs = {
ids: Array<Maybe<Scalars['ID']>>;
};(我真的不明白为什么它生成为可能的类型,因为graphql模式强制我只使用I(字符串)数组的参数进行查询)
在我的解析器中,我需要调用一个接受字符串数组的服务。一切都如预期的那样工作(使用@ts-忽略),但现在我需要修复我的类型。
const { orderIds } = args;
const result = getOrder(orderIds);我有一个只有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);我目前得到了错误- "TS2345:'Maybe[]‘类型的参数不能分配给’string[]‘类型的参数。“
任何帮助都非常感谢
发布于 2021-04-07 16:04:28
如果您确信不应该是一个可能的类型,您可以使用它:
type Maybe<T> = T | null;
const maybeArray: Maybe<string>[] = [];
let stringArray: string[] = maybeArray as string[];或者在你的情况下
getOrders(ids as string[]);发布于 2022-11-16 15:31:45
要删除Maybe,需要过滤不可空项
const nonNullable = <T>(value: T): value is NonNullable<T> =>
value !== null && value !== undefined
getOrders(ids.filter(nonNullable));但是,如果要从模式中删除Maybe,则需要在graphql模式中使用感叹号!作为必需字段
https://stackoverflow.com/questions/66989605
复制相似问题