DEV Community

David Garcia
David Garcia

Posted on

3 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? 🚀

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay