问题描述
我开始认为我想做的事情没有简单的解决方案.我有一个包含10个参数的类,其中大多数是可选的.为简单起见,我将仅使用3个参数来描述我的问题.
I'm starting to think there is no easy solution for what I want to do. I have a class that takes in 10 parameters, most of them are optional. For simplicity reasons I will depict my issue using only 3 parameters.
我希望我能够调用PageConfig构造函数,而忽略一些或所有可选参数.例如
I want my to be able to call the PageConfig Constructor omitting some or all of the optional parameters. e.g
new PageConfig({getList: this.getList})
new PageConfig({getList: this.getList, canDelete: false });
new PageConfig({getList: this.getList, isSliding: true });
我试图通过以下方式做到这一点.
I've tried to do this the following way.
export class PageConfigArgs {
canDelete?: boolean;
isSliding?: boolean;
getList: (pagingInfo: PagingInfo) => Observable<any>;
}
export class PageConfig extends PageConfigArgs {
constructor({
isSliding = false,
canDelete = true
}: PageConfigArgs) {}
}
由于需要getList,因此构造函数中没有默认值.
但是问题是我不知道如何从构造函数中引用getList来将其分配给内部的.
Since getList is required it doesn't have a default in the constructor.
but the issue is I don't know how to reference getList from the constructor to assign it to the internal one.
如何创建包含可选参数和必需参数的新配置类?
How can I create a new configuration class mixing optional and required parameters?
修改我的主要重点是创建简单的初始化,不需要初始化后再配置配置类.
EditMy main focus is to create easy initialization which doesn't require me to configure the configuration class after initialization.
修改由于重复关闭,所以我没有意识到我需要在类内部的配置中声明我想要的所有属性.有关解决方法,请参见前面的问题
EditClosed as duplicate, I didn't realize I needed to declare all of the properties I wanted in the config inside my class. See previous question for resolution
推荐答案
我了解内部人员"是指班级成员.
I understand that by the "internal one" you mean the member of the class.
可以通过在构造函数体内进行分解来解决问题.
The problem can be solved by destructuring within the constructor's body.
然后,您可以将object属性分配给类成员.
Then you can assign the object property to a class member.
export class PageConfigArgs {
canDelete?: boolean;
isSliding?: boolean;
getList: (pagingInfo: PagingInfo) => Observable<any>;
}
export class PageConfig extends PageConfigArgs {
private getList: (pagingInfo: PagingInfo) => Observable<any>;
constructor(args: PageConfigArgs) {
const { isSliding = false, canDelete = true } = args;
this.getList = args.getList;
}
}
这篇关于带有C#的构造函数的打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!