Home > other >  Why is the boolean value in FormRecord possibly undefined?
Why is the boolean value in FormRecord possibly undefined?

Time:12-16

I am trying to make an assignment in the handler method but the type of this.form.value is Partial<{ [key: string]: boolean }> and the compiler is telling me that the string index signatures are incompatible and that undefined is not assignable to boolean.

I don't understand how the boolean is considered to be possibly undefined when the control is explicitly created with an initial value that is not null or undefined.

How can I handle this typing without having to use the null forgiving operator? (!)

export interface TableColumn {
  visible?: boolean;
  key: string;
}

...

@Input() public columns: TableColumn[] = [];

public form: FormRecord<FormControl<boolean>>;

constructor(private _fb: FormBuilder) {
  this.form = this._fb.nonNullable.record({});
}

public ngOnInit(): void {
  this.columns.forEach((col: TableColumn) => {
    const control = this._fb.nonNullable.control<boolean>(col.visible ?? true);
    this.form.addControl(col.key, control);
  })
}

public handler(): void {
  const val: Record<string, boolean> = this.form.value;
  const value: { [key: string]: boolean } = this.form.value;
}

CodePudding user response:

You can assign it the type it is telling you to:

const val: Partial<{[x: string]: boolean}> = this.form.value;

or just don't assign a type and let typescript infer it.

const val = this.form.value; // type is Partial<{[x: string]: boolean}>

The reason that the boolean can be undefined is that you can index a string that is not a key.

Example:

this.form.value["someRandomString"] // undefined

This is the advantage of using Partial, it forces you to check this condition.

CodePudding user response:

Because this.form.value is Partial<{ [x: string]: boolean }>, so you could use type assertion:

const val: Record<string, boolean> = this.form.value as Record<string, boolean>;
const value: { [key: string]: boolean } = this.form.value as Record<string, boolean>;

Or, just make the compiler happy and say the booleans could be undefined:

const val: Record<string, boolean | undefined> = this.form.value;
const value: { [key: string]: boolean | undefined } = this.form.value;
  • Related