微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对象可能是'undefined'.ts2532,带有可选参数

如何解决对象可能是'undefined'.ts2532,带有可选参数

我有代码

export default class MyRandomClass {
  private posFloat32Array?: Float32Array;
  private otherArgument?: number;

  constructor(params:MyRandomClass = {} as MyRandomClass) {
    const {
      posFloat32Array,otherArgument,} = params;

    this.posFloat32Array = (posFloat32Array !== undefined) ? posFloat32Array : new Float32Array();
    this.otherArgument = (otherArgument !== undefined) ? otherArgument : 0;
  }

  classMethod():void {
    const total = this.posFloat32Array?.length + 3; //error
  }
}

该对象不可能是未定义的,但我仍然会收到错误消息。 我的目的是拥有一个可以用不同方式提供的参数构造的类,以便输出数据将始终相同。如this示例中那样,这正在模拟构造器过载。

我想应该有一种可能的方法,使函数/类具有可选参数,并告诉编译器该参数已实际传入,否则,未定义的场景已得到相应管理。

如何用可选参数来处理?

编辑:根据我的研究,以here中的代码示例为例,不可能使您的类变量成为可选变量,并使编译器知道它们不会被未定义并在您的方法中使用它们,而无需一个单独的参数类型,使该类型参数成为可选参数,而使类变量不是可选参数,如果类很大,则这很冗长。我想确认这是处理打字稿类中可选参数的有效方法还是最佳方法

解决方法

编译器在抱怨,因为您已将该属性定义为?的可选属性。问题出在您的声明上。

由于您有一个构造函数,并且在构造函数中始终将posFloat32ArrayotherArgument设置为显式值,因此不需要将这些属性标记为可选。您应该删除将这些属性标记为可选。

那我什么时候希望类属性是可选的?

这是一个很好的问题!如果您没有显式实现构造函数,或者没有在构造函数中显式设置这些值,则此时可能需要将属性标记为可选。例如,下面的类示例可以在不显式定义那些值的情况下实例化。将它们标记为可选可能是一个很好的用例。

class MyRandomClass {
  private posFloat32Array?: Float32Array;
  private otherArgument?: number;

  classMethod():void {
    const total = this.posFloat32Array?.length ?? 0 + 3;
  }
}
,

您需要分离您的接口,因为该类不再描述传入的参数对象。我的回答显示了一种更优雅的设置默认值的方式。并且由于您正在设置默认值,接口上的参数是可选的,但它们在类中得到保证(注意问号移动的位置)。这应该适合您:

interface MyNotSoRandomInterface {
  posFloat32Array?: Float32Array;
  otherArgument?: number;
}

export default class MyRandomClass {
  private posFloat32Array: Float32Array;
  private otherArgument: number;

  constructor(params:MyNotSoRandomInterface = {} as MyNotSoRandomInterface) {
    const {
      posFloat32Array =  new Float32Array(),otherArgument = 0,} = params;

    this.posFloat32Array = posFloat32Array;
    this.otherArgument = otherArgument;
  }

  classMethod():void {
    const total = this.posFloat32Array.length + 3; //no errors!
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。