angularangular-formstsconfigstrictnullchecks

Better method to map formgroup controls to optional function parameter with StrictNullChecks on


So recently on my Angular project I turned on StrictNullChecks and have been going through and fixing errors. One error I found that I've been stumped by has been with FormControls/FormGroups.

I have 2 interfaces:

interface SearchCriteria {
    locationID: string,
    filters: {
        group?: SearchFilterCode
        name?: SearchFilterCode
        shift?: SearchFilterCode
    }
}

interface SearchFilterCode {
    codeID: number,
    codeText: string
}

These interfaces are used for a small filtering popup for a table.

I created a FormGroup to match the filters object:

filterGroup = new FormGroup({
    group: new FormControl<SearchFilterCode>(null)
    ...
});

The issue that I'm having is that after strictNullChecks was enabled, I had to add a null type to the formControl: FormControl<SearchFilterCode | null>(null) because of StrictNullChecks.

However, when I try to then map it to an object for an http request:

const obj: SearchCriteria = {
    locationID: 'abcdefg',
    filters: this.filterGroup.value
}

I get this error Type 'SearchFilterCode | null' is not assignable to type 'SearchFilterCode | undefined'. So I changed the formControl to FormControl<SearchFilterCode | undefined>(undefined) However, I instead got this error:

Type 'SearchFilterCode | undefined | null' is not assignable to type 'SearchFilterCode | undefined'

Is there a way to deal with the fact that FormControl adds a null type to each value and StrictNullChecks differentiates between null and undefined? I'm hoping I don't have to remap the filtersGroup.value object to a new object and just make all nulls undefined.


Solution

  • Take a look at the NonNullableFormBuilder

    That should solve your problem.