Skip to content

Commit

Permalink
fix(forms): FormBuilder.group return right type with shorthand parame…
Browse files Browse the repository at this point in the history
…ters. (#48084)

Extract AbstractControlOptions from type when used in shorthand parameters on FormBuilder.group

Fixes 48073

PR Close #48084
  • Loading branch information
JeanMeche authored and dylhunn committed Nov 17, 2022
1 parent 9baefd0 commit a12a120
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
10 changes: 9 additions & 1 deletion packages/forms/src/form_builder.ts
Expand Up @@ -38,6 +38,14 @@ type ValidatorConfig = ValidatorFn|AsyncValidatorFn|ValidatorFn[]|AsyncValidator
*/
type PermissiveControlConfig<T> = Array<T|FormControlState<T>|ValidatorConfig>;

/**
* Helper type to allow the compiler to accept [XXXX, { updateOn: string }] as a valid shorthand
* argument for .group()
*/
interface PermissiveAbstractControlOptions extends Omit<AbstractControlOptions, 'updateOn'> {
updateOn?: string;
}

/**
* ControlConfig<T> is a tuple containing a value of type T, plus optional validators and async
* validators.
Expand Down Expand Up @@ -82,7 +90,7 @@ export type ɵElement<T, N extends null> =
// FormControlState object container, which produces a nullable control.
[T] extends [FormControlState<infer U>] ? FormControl<U|N> :
// A ControlConfig tuple, which produces a nullable control.
[T] extends [PermissiveControlConfig<infer U>] ? FormControl<Exclude<U, ValidatorConfig>|N> :
[T] extends [PermissiveControlConfig<infer U>] ? FormControl<Exclude<U, ValidatorConfig| PermissiveAbstractControlOptions>|N> :
FormControl<T|N>;

// clang-format on
Expand Down
16 changes: 16 additions & 0 deletions packages/forms/test/form_builder_spec.ts
Expand Up @@ -189,6 +189,22 @@ describe('Form Builder', () => {
expect(g.asyncValidator).toBe(null);
});

it('should create groups with shorthand parameters and with right typings', () => {
const form = b.group({
shorthand: [3, Validators.required],
shorthand2: [5, {validators: Validators.required}],
});

expect((form.get('shorthand')?.value)).toEqual(3);
expect(((form.get('shorthand2')!.value ?? 0) + 0)).toEqual(5);


const form2 = b.group({
shorthand2: [5, {updateOn: 'blur'}],
});
expect(((form2.get('shorthand2')!.value ?? 0) + 0)).toEqual(5);
});

it('should create control arrays', () => {
const c = b.control('three');
const e = b.control(null);
Expand Down

0 comments on commit a12a120

Please sign in to comment.