DEV Community

David Garcia
David Garcia

Posted on

3 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? ๐Ÿš€

Quadratic AI

Quadratic AI โ€“ The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo ๐Ÿ“Šโœจ

Top comments (0)

Image of PulumiUP 2025

Transform Your Cloud Infrastructure

Join PulumiUP 2025 on May 6 for Expert Insights & Demos.

Register Now