TypeScript抱怨“隐式”或“可能未定义”,即使不可能

乔纳森

我试图将对象中的属性(如果存在且大于0)减少1,但是无论我如何尝试,TypeScript都不会编译此代码。

interface IStatus {
  [key: string]: number | undefined; // <= I don't want undefined here but it complains since the params are optional
  burning?: number;
  firing?: number;
}

class Thing {
  public status: IStatus = {};
  private processStatus() {
    for (const key in this.status) {
      if (
        this.status.hasOwnProperty(key) &&
        this !== undefined &&
        this.status !== undefined &&
        this.status[key] !== undefined && // <= Complains about implicit any without the index signature
        this.status[key] > 0 // <= Complains about possibly undefined with the index signature
      ) {
        this.status[key]--;
      }
    }
  }
}
插口

在Typescript中,具有索引签名的类型的所有属性都必须遵守该签名,这就是为什么它要求您将其包括undefined在索引值中的原因。这是一种确保属性类型一致的机制,无论您使用括号符号(status["burning"])还是点符号(status.burning访问属性都是如此

但是您可以通过使用交集类型来组合索引签名和其他属性来解决此问题:

type IStatus = {
  [key: string]: number; // <= No undefined here anymore
} & {
  burning?: number;
  firing?: number;
}

使用该方法,this.status[key]可以推断出具有type number,但是this.status.burning可以推断出具有type number | undefined

如前所述,您将要小心,因为现在您可以burning通过访问属性的方式更改属性的推断类型如果使用this.status["burning"],则类型推断为just number

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

当不可能时,“对象可能未定义”

不可能的隐式移动操作?

变量不可能设置为“未定义”

为什么 Typescript 在 useMemo 中说 X 可能是未定义的,而此时它永远不可能是未定义的

编译器抱怨“缺少返回语句”,即使不可能达到缺少返回语句的条件

即使使用if语句,对象也可能未定义

对象可能是“未定义”,即使它不能

当我检查值是否在上一行中定义时,为什么Typescript抱怨一个可能的未定义值?

TS编译器没有抱怨可能的未定义对象销毁?

React Native:Typescript - 数据可能未定义

Ref对象可能是未定义的TypeScript React

Protobuf 生成的 Python 包内部的隐式相对导入使得从外部导入变得不可能

道具可能未定义

了解“不可能”

不可能的NullPointerException

即使没有变化也不可能快进

C#:即使不可能,也会发出空警告

打字稿认为对象可能未定义,即使它已定义

打字稿“错误TS2532:对象可能是'未定义'”,即使经过未定义的检查

从函数早返回:null,显式未定义,隐式未定义?

猫鼬即使在等待时也返回未定义的状态。任何猜测可能是错误的吗?

即使我检查对象是否存在条件也可能未定义对象

没有参数的步骤定义不可能吗?

在ListFragment中创建自定义ListView是不可能的

函数的隐式声明和未定义的引用

Redux-使不可能的状态变为不可能

逆矩阵不可能

消除不可能的选择

REST 用户不可能?