【发布时间】:2023-01-02 19:31:23
【问题描述】:
我的 HTML 代码有问题,编译器死于:
Type 'CustomItem[] | null | undefined' is not assignable to type 'CustomItem[]
| undefined'.
Type 'null' is not assignable to type 'CustomItem[] | undefined'.
HTML 代码看起来像这样,我什至检查 Observable NOT 在 *ngIf 中是否为 null。
<library-select
*ngIf="(data$ | async) !== null"
[data]="(data$ | async)"
(itemSelected)="itemSelected($event)"
></library-select>
在相应的 .ts 文件中,实例化这个 Observable 的代码如下所示:
@Select(SelectState.getData) data$: Observable<CustomItem[] | undefined>;
同样,不可能有 null 滑入。现在在商店中,项目数组最初是未定义的,然后由 http 请求响应启动,如下所示:
@Action(HttpSuccess)
private httpSuccess(ctx: StateContext<SelectStateModel>, action: HttpSuccess) {
const items: CustomItem[] = [];
action.result?.portfolios?.forEach((value, index) => {
items.push({
value: value?.username,
top: {
topMainText: value?.username,
},
bottom: {
bottomMainText: value?.userType
},
id: value?.userId.toString()
});
再一次,我不明白为什么编译器或打字稿会推断出空数据类型。
我使用的是 Angular 14.2,我正在使用 NGXS 状态管理。
我尝试在 HTTP 请求的整个持续时间内注销每个相关变量的数据类型,存储初始化,甚至当我读取组件 .ts 文件中的可观察对象时,它总是未定义或 CustomItem[],没有一次是 null .我使用标签上的 *ngIf 指令检查空数据类型,希望它不会显示任何东西,如果它真的*可以*是一个空值(看起来它不能),但无济于事。
【问题讨论】:
标签: html angular typescript typeerror ngxs