Skip to content

Instantly share code, notes, and snippets.

@theer1k
Created August 11, 2023 11:36
Show Gist options
  • Save theer1k/b2c8c0f133c288ac4db6ddf583265b2d to your computer and use it in GitHub Desktop.
Save theer1k/b2c8c0f133c288ac4db6ddf583265b2d to your computer and use it in GitHub Desktop.
Angular WithControlsFrom type safe form
import {
FormControl,
FormGroup,
NonNullableFormBuilder
} from '@angular/forms';
// 👇 This is a helper to bind any interface with the FormGroup generating a type safe form matching existing keys and FormControl type 🙂
export type WithControlsFrom<T> = {
[P in keyof T]?: FormControl<T[P]>;
};
export interface UserModel {
id: number | null;
name: string;
gender: string;
}
class SomeComponent {
userForm!: FormGroup<WithControlsFrom<UserModel>>;
constructor(
private readonly _formBuilder: NonNullableFormBuilder)
{
this.userForm = new FormGroup<WithControlsFrom<UserModel>>({
id: this._formBuilder.control(null),
name: this._formBuilder.control('Father Horse'),
gender: this._formBuilder.control(777), // Throws: Type 'FormControl<number>' is not assignable to type 'FormControl<string>'. Type 'number' is not assignable to type 'string'.
xyz: this._formBuilder.control('') // Throws: Object literal may only specify known properties, and 'xyz' does not exist in type 'WithKeysFrom<UserModel>'.
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment