I’m trying to use a radio button to get a boolean value from a user. The value should default to null, as the user hasn’t answered anything yet. Here is the current implementation that works, but is ugly.
Here is my current implementation:
export class SomeComponent {
form = this.fb.group({
booleanInput: [null as unknown as boolean, [Validators.required]],
});
constructor(private readonly fb: FormBuilder) {};
getBoolValue() {
return this.form.control.booleanInput.value; // return type boolean
}
}
Previously I tried without the as unknown as boolean
, but when the attempting to set the value (particularly in the case of unit tests) or get the value, the implied type is null
, which is not what we want.
additionally, I tried with the FormControl constructor, but that has a return type of boolean | null
when getting the value. example:
export class SomeComponent {
form = this.fb.group({
booleanInput: new FormControl<boolean | null>(null, [Validators.required]),
});
constructor(private readonly fb: FormBuilder) {};
getBoolValue() {
return this.form.control.booleanInput.value; // return type boolean | null
}
}
Any insight or best practice suggestions would be appreciated!
Daron Schmit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.