打字稿解构与所需参数 [英] Typescript destructuring with required parameter
问题描述
编辑抱歉,我的问题有点不清楚.我要强制始终需要getList参数.所以我没有默认值.例如,我希望用户始终提供一个获取列表
Edit Sorry my question was a bit unclear. I want to enforce that the getList Parameter is always required. So I don't have a default value for it. e.g I want the user always to supply a getlist
我正在尝试创建一个具有一些可选参数和一些必需参数的构造器
I'm trying to create a constuctor with some optional parameters and some required
export class PageConfig {
constructor({
isSliding = false,
}: {
isSliding?: boolean
getList: (pagingInfo: PagingInfo) => Observable<any>
} = { }) { }
}
执行此操作时出现错误
类型"{}"中缺少getList,但类型...中必需.
getList is missing in type '{}' but required in type ...
我希望能够在像这样的类中使用它:
I would like to be able to use this in a class like so:
class UsersPage {
config = new pageConfig({ this.getList })
getList(pagingInfo: PagingInfo) {
// do work...
}
}
注意::我已为该示例简化了类,但我拥有更多的属性,我想利用解构方法,因此无需配置其他类的实例化.比声明中的
Note: I've simplified the class for this example but I have a lot more properties, I'd like to leverage desturcturing so I don't have to configure the instantiation of my classes other than from the declaration
如何强制销毁过程中必须传递getList?
How can I enforce that getList must be passed during destructuring?
推荐答案
您对PageConfig构造函数参数使用默认值{}
,但是在类型中按需标记了getList
.如果我对您的理解正确,则希望始终设置构造函数参数和getList
,因此将代码更改为:
You use a default value {}
for the PageConfig constructor argument, but you marked getList
as required in the type. If I understand you correctly, you want to have the constructor argument and getList
always set, so change your code to:
export class PageConfig {
constructor({
getList,
isSliding = false
}: {
getList: (pagingInfo: PagingInfo) => Observable<any>;
isSliding?: boolean;
}) {
… // use getList and isSliding
}
}
这种语法(使用默认值进行销毁)有时会有点麻烦.它变得更清晰,当你提取构造函数参数类型.
This syntax (destructuring with default values) can be a bit cumbersome sometimes. It gets clearer, when you extract the constructor argument type.
这篇关于打字稿解构与所需参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!