【发布时间】:2021-02-03 13:38:50
【问题描述】:
我有这个代码:
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 获取代码示例,不可能让你的类变量可选并且让编译器知道它们不会是未定义的并在你的方法中使用它们,而不需要分开参数的类型,使这种类型的参数是可选的,而类变量不是可选的,如果类很大,这有点冗长。我想确认这是否是处理打字稿类中的可选参数的有效方法或最佳方法。
【问题讨论】:
-
既然你肯定在构造函数中分配了私有字段,你可以去掉它们的问号。
-
所以问号只适用于构造函数参数?
-
在这种情况下是正确的。
标签: typescript optional-arguments