我正在使用 GraphQL,并且希望严格输入gql
。是否有可能使result
变量的形状ResultData
即使用最新版本的 TypeScript。它只与输入有关,与运行时无关。
interface Data {
one: string;
two: number;
three: {
four: string;
five: {
six: Date;
};
};
}
// true means that this field must be added to query
type RecursivePartial<T> = {[P in keyof T]?: RecursivePartial<T[P]> | true};
function gql<T>(fields: RecursivePartial<T>) {
// Some code about generating GraphQL query
}
const result = gql<Data>({one: true, three: {five: {six: true}}});
// type ResultData {
// one: string;
// three: {
// five: {
// six: Date;
// };
// };
// }
这在操场上对我有用:
interface Data {
one: string;
two: number;
three: {
four: string;
five: {
six: Date;
};
};
}
// Prevent widening of true to boolean in queries
type RecursivePartial1 = { [k: string]: RecursivePartial1 | true };
// true means that this field must be added to query
type RecursivePartial<T> = RecursivePartial1 & { [P in keyof T]?: RecursivePartial<T[P]> | boolean };
type RecursivePick<T, Q extends RecursivePartial<T>> =
{ [P in keyof T & keyof Q]:
Q[P] extends RecursivePartial<T[P]> ? RecursivePick<T[P], Q[P]> : T[P] };
function gql<T, Q extends RecursivePartial<T>>(data: T, fields: Q): RecursivePick<T, Q> {
// Some code about generating GraphQL query
}
declare const data: Data;
const result = gql(data, { one: true, three: { five: { six: true } } });
// type ResultData {
// one: string;
// three: {
// five: {
// six: Date;
// };
// };
// }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)