DEV Community

David Garcia
David Garcia

Posted on

4 1 1

๐Ÿ“Œ Strongly Typed Forms in Angular Without Duplicating Interfaces

Angularโ€™s documentation suggests defining both interfaces and a manually typed form model. But with TypeScript and recursive types, we can avoid duplication! ๐Ÿš€

Define a generic type:

export type IToForm<T> = {
  [K in keyof T]: T[K] extends Array<infer U>
    ? FormArray<U extends object ? FormGroup<IToForm<U>> : FormControl<U>>
    : T[K] extends Date
    ? FormControl<T[K]>
    : T[K] extends object
    ? FormGroup<IToForm<T[K]>>
    : FormControl<T[K]>>;
};
Enter fullscreen mode Exit fullscreen mode

Now, create automatically typed forms:

customerForm = new FormGroup<IToForm<Customer>>({
  id: new FormControl(''),
  email: new FormControl(''),
  firstName: new FormControl(''),
  lastName: new FormControl(''),
  addresses: new FormArray([]),
  preferences: new FormGroup({
    newsletter: new FormControl(false),
    language: new FormControl('en'),
  }),
});
Enter fullscreen mode Exit fullscreen mode

โœ… Benefits:
๐Ÿ”น No key name errors.
๐Ÿ”น Autocomplete in the editor.
๐Ÿ”น Less repetitive code.
๐Ÿ”น If you change the model, the entire code will be affected.

๐Ÿ“ข Have you tried this approach in your Angular forms? ๐Ÿš€

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series ๐Ÿ“บ

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series ๐Ÿ‘€

Watch the Youtube series