Home > Mobile >  Typed form group, empty array interpreted as 'never'
Typed form group, empty array interpreted as 'never'

Time:01-24

Why is empty array interpreted as never when using Angulars' NonNullableFormBuilder?

public form = this.fb.group({
    item: [[]],
});

And then:

this.form .patchValue({
      item: someValue,
});

I receive: Type 'SomeType[]' is not assignable to type 'never'.

How to make it work?

CodePudding user response:

That's due to the definition of group()

export abstract class NonNullableFormBuilder {
  abstract group<T extends {}>(
      controls: T,
      options?: AbstractControlOptions|null,
      ): FormGroup<{[K in keyof T]: ɵElement<T[K], never>}>;
}

Which can be narrowed down to :

function foo<T>(t: T): T {
    return t;
}

const a = foo([]);  // never

const b = foo([] as Array<number>); // number[]

The constant empty array is inferred as never[]. Casting your array will fix the issue for you.

Playground

CodePudding user response:

Maybe you should try setValue() instead of patchValue().

this.form.setValue({
  item:someValue
});
  • Related