Created
August 11, 2023 11:36
-
-
Save erikunha/b2c8c0f133c288ac4db6ddf583265b2d to your computer and use it in GitHub Desktop.
Angular WithControlsFrom type safe form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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