我声明了一个接口如下:

export interface Material {
    readonly id?: number;
    pictureUrl?: string;
    word?: string;
}

实际在某种情况下,这里的id是肯定存在的,这时我需要利用做一些处理,但是我在用的时候才发现事情并没有那么简单。

使用方法如下:

this.materialList.forEach((material, index) => {
    materialConfig[material.id] = index;
});

在使用时,ts飘红了.

具体给出的警告是这样的:Type 'undefined' cannot be used as an index type.。因为在定义接口的时候id是有可能为空的(即undefined),而undefind不能被用做索引值,所以ts向我给出了警告!

那么遇到这种问题,该如何处理呢?

解决方案

这个时候处理方法有两种:

  1. 在取值之前先判断变量已经存在;
  2. 强制断言该变量存在。

方案1

先判断变量是否存在,当存在时才使用它。

this.materialList.forEach((material, index) => {
    if (material.id) {
        materialConfig[material.id] = index;
    }
});

方案2

在变量后面加上!强制断言变量已经存在。

this.materialList.forEach((material, index) => {
    materialConfig[material.id!] = index;
});

我是尾巴

使用方案2的时候代码飘黄了,警告Forbidden non-null assertion.,最终我使用了方案1。