Skip to content

Instantly share code, notes, and snippets.

@JPBM135
Last active September 6, 2024 20:09
Show Gist options
  • Save JPBM135/d5e3046bb16eb23cf418f4f7d01797bc to your computer and use it in GitHub Desktop.
Save JPBM135/d5e3046bb16eb23cf418f4f7d01797bc to your computer and use it in GitHub Desktop.
Obj to Form
import { FormGroup, FormArray, FormControl } from '@angular/forms';
import { InputMaybe } from '@generated/graphql';
type ExtractTypeFromInputMaybe<T> = NonNullable<T> extends InputMaybe<infer U> ? U : T;
type FormularizeRecord<T> =
ExtractTypeFromInputMaybe<T> extends Record<string, unknown>
? FormGroup<{ [K in keyof T]: FormularizeObject<NonNullable<T[K]>> }>
: never;
type FormularizeArray<T> = T extends Array<unknown> ? FormArray<FormularizeObject<T[number]>> : never;
type FormularizePrimitive<T> = ExtractTypeFromInputMaybe<T> extends boolean ? FormControl<boolean> : never;
type ValueOf<T> = T extends boolean | string | number | null | undefined ? `${T}` | T : never;
type FormularizeControl<T> = T extends FormControl<unknown> | FormGroup<any> | FormArray<any>
? T
: FormControl<ValueOf<ExtractTypeFromInputMaybe<T>>>;
export type FormularizeObject<T> =
FormularizeRecord<T> extends never
? FormularizeArray<T> extends never
? FormularizePrimitive<T> extends never
? FormularizeControl<T>
: FormularizePrimitive<T>
: FormularizeArray<T>
: FormularizeRecord<T>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment