打字稿中有没有一种方法可以仅在存在时将可选参数传递给构造函数?
我有一个对象,它有一个带有可选参数的构造函数,如下所示:
class example{
constructor(a: string,b: string,c: string,d?:string){
//...
}
}
这个类将在另一个方法中实例化。像这样:
function createExample(a: string,b: string,c: string,d?:string){
return new example(a,b,c,d)
}
但我只想在函数 createExample() 收到时传递“d”参数。 javascript/typescript 有没有办法做到这一点。像这样:
我只想传递参数 d 仅当它存在时,我希望我不必执行 if 来检查它,因为如果我有更多可选参数,它会变得复杂。 javascript/typescript 有没有办法做到这一点。比如:
function createExample(a: string,b: string,c: string,d?:string){
return new example(a,b,c,d?)
}
或者我应该将 instatiaton 保留为正常的“d”参数,并且如果未定义它,则应将其作为未定义传递?
I have an object that has a constructor with an optional parameter like this:
class example{
constructor(a: string,b: string,c: string,d?:string){
//...
}
}
This class will be instatiated inside another method. Like this:
function createExample(a: string,b: string,c: string,d?:string){
return new example(a,b,c,d)
}
But i only want to pass the "d" parameter if the function createExample() received. Is there a way in javascript/typescript to do this. Something like:
I want to pass the parameter d only if it exists, and I hope I don't have to do an if that checks this, because if I have more optional parameters it can get complicated. Is there a way in javascript/typescript to do this. Something like:
function createExample(a: string,b: string,c: string,d?:string){
return new example(a,b,c,d?)
}
Or should I just leave the instatiaton with the normal "d" parameter, and in case it is not defined, it should be passed as undefined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您将
D
的类型定义为可能未定义,则可以将其传入If you define the type for
D
as potentially undefined, you can just pass it in是的,正是这个。 JavaScript 对待缺失参数和作为参数传递的
未定义
的态度相同1 - 两者最终都会得到未定义
或默认参数。所以它很简单,如果你真的关心,你可以对数组使用扩展语法:
1:除了
arguments.length
和其余参数语法Yes, exactly this. JavaScript treats missing arguments and
undefined
being passed as an argument the same1 - both end up with anundefined
or defaulted parameter. So it's as simple asIf you really care, you can use spread syntax with an array:
1: except for
arguments.length
and rest parameter syntax