This content originally appeared on DEV Community and was authored by David Garcia
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]>>;
};
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'),
}),
});
✅ 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? 🚀
This content originally appeared on DEV Community and was authored by David Garcia

David Garcia | Sciencx (2025-02-04T21:12:06+00:00) 📌 Strongly Typed Forms in Angular Without Duplicating Interfaces. Retrieved from https://www.scien.cx/2025/02/04/%f0%9f%93%8c-strongly-typed-forms-in-angular-without-duplicating-interfaces/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.