DEV Community

David Garcia
David Garcia

Posted on

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

$150K MiniMax AI Agent Challenge — Build Smarter, Remix Bolder, Win Bigger!

Join the $150k MiniMax AI Agent Challenge — Build your first AI Agent 🤖

Developers, innovators, and AI tinkerers, build your AI Agent and win $150,000 in cash. 💰

Read more →

Top comments (0)

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

👋 Kindness is contagious

Take a moment to explore this thoughtful article, beloved by the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A heartfelt "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay