Skip to content

Commit a12a120

Browse files
JeanMechedylhunn
authored andcommitted
fix(forms): FormBuilder.group return right type with shorthand parameters. (#48084)
Extract AbstractControlOptions from type when used in shorthand parameters on FormBuilder.group Fixes 48073 PR Close #48084
1 parent 9baefd0 commit a12a120

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

packages/forms/src/form_builder.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ type ValidatorConfig = ValidatorFn|AsyncValidatorFn|ValidatorFn[]|AsyncValidator
3838
*/
3939
type PermissiveControlConfig<T> = Array<T|FormControlState<T>|ValidatorConfig>;
4040

41+
/**
42+
* Helper type to allow the compiler to accept [XXXX, { updateOn: string }] as a valid shorthand
43+
* argument for .group()
44+
*/
45+
interface PermissiveAbstractControlOptions extends Omit<AbstractControlOptions, 'updateOn'> {
46+
updateOn?: string;
47+
}
48+
4149
/**
4250
* ControlConfig<T> is a tuple containing a value of type T, plus optional validators and async
4351
* validators.
@@ -82,7 +90,7 @@ export type ɵElement<T, N extends null> =
8290
// FormControlState object container, which produces a nullable control.
8391
[T] extends [FormControlState<infer U>] ? FormControl<U|N> :
8492
// A ControlConfig tuple, which produces a nullable control.
85-
[T] extends [PermissiveControlConfig<infer U>] ? FormControl<Exclude<U, ValidatorConfig>|N> :
93+
[T] extends [PermissiveControlConfig<infer U>] ? FormControl<Exclude<U, ValidatorConfig| PermissiveAbstractControlOptions>|N> :
8694
FormControl<T|N>;
8795

8896
// clang-format on

packages/forms/test/form_builder_spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,22 @@ describe('Form Builder', () => {
189189
expect(g.asyncValidator).toBe(null);
190190
});
191191

192+
it('should create groups with shorthand parameters and with right typings', () => {
193+
const form = b.group({
194+
shorthand: [3, Validators.required],
195+
shorthand2: [5, {validators: Validators.required}],
196+
});
197+
198+
expect((form.get('shorthand')?.value)).toEqual(3);
199+
expect(((form.get('shorthand2')!.value ?? 0) + 0)).toEqual(5);
200+
201+
202+
const form2 = b.group({
203+
shorthand2: [5, {updateOn: 'blur'}],
204+
});
205+
expect(((form2.get('shorthand2')!.value ?? 0) + 0)).toEqual(5);
206+
});
207+
192208
it('should create control arrays', () => {
193209
const c = b.control('three');
194210
const e = b.control(null);

0 commit comments

Comments
 (0)