【问题标题】:HTML compilation gets blocked by forbidden 'null' data type, even though null can't be a valueHTML 编译被禁止的“null”数据类型阻止,即使 null 不能是一个值
【发布时间】: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


    【解决方案1】:

    假,空,未定义。所有不同的值,但可以松散地使用相同。关键词:宽松。

    您的模板指定查找 null:*ngIf="(data$ | async) !== null"

    但是您的 observable 并没有说它会分发 null:@Select(SelectState.getData) data$: Observable&lt;CustomItem[] | undefined&gt;;

    你可观察的只能给CustomItem[]undefined。因此,没有办法像您所做的那样检查 null 值是合理的。

    将其切换为检查未定义,应该没问题:*ngIf="(data$ | async) !== undefined"

    或者,放宽等价性检查:*ngIf="(data$ | async) != null"

    false、null 和 undefined 都是 ==,但不是 ===,所以 != 应该有效,但 !== 肯定不行,因为它们都是不同的值。

    【讨论】:

    • *ngIf 检查正是因为它首先抛出了错误。我不能应用 *ngIf="(data$ | async) !== undefined 因为这意味着当数据未定义时我不显示选择,这是一个真实的可能性,但我还是希望它显示。我尝试了第二种解决方案,不幸的是它也不起作用。:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2018-07-06
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多