最近在我的 Angular 项目中,我打开了 StrictNullChecks 并一直在检查和修复错误。我发现我一直被 FormControls/FormGroups 所困扰的一个错误。
我有2个接口:
interface SearchCriteria {
locationID: string,
filters: {
group?: SearchFilterCode
name?: SearchFilterCode
shift?: SearchFilterCode
}
}
interface SearchFilterCode {
codeID: number,
codeText: string
}
这些接口用于表格的小型过滤弹出窗口。
我创建了一个 FormGroup 来匹配
filters
对象:
filterGroup = new FormGroup({
group: new FormControl<SearchFilterCode>(null)
...
});
我遇到的问题是,启用 strictNullChecks 后,我必须向 formControl 添加 null 类型:
FormControl<SearchFilterCode | null>(null)
,因为 StrictNullChecks。
但是,当我尝试将其映射到 http 请求的对象时:
const obj: SearchCriteria = {
locationID: 'abcdefg',
filters: this.filterGroup.value
}
我收到此错误
Type 'SearchFilterCode | null' is not assignable to type 'SearchFilterCode | undefined'
。所以我将 formControl 更改为 FormControl<SearchFilterCode | undefined>(undefined)
但是,我却得到了这个错误:
Type 'SearchFilterCode | undefined | null' is not assignable to type 'SearchFilterCode | undefined'
是否有办法处理 FormControl 为每个值添加 null 类型以及 StrictNullChecks 区分
null
和 undefined
的事实?我希望我不必将 filtersGroup.value
对象重新映射到新对象,只需使所有空值未定义即可。
这应该可以解决你的问题。