【发布时间】:2020-03-30 21:14:23
【问题描述】:
我的构造函数开始变长,而且不是我喜欢的样子。我更愿意将一个对象传递给我的构造函数,这样我就可以按名称引用字段。现在上课了。
export class Group {
id: string;
constructor(
public title: string,
public isPublic: boolean,
public comments: string = '',
public targets: Target[] = [],
public owner?: string,
id?: string
) {
this.id = typeof id === 'undefined' ? uuid() : id;
}
associatedTargets(targets: Target[]) {
return targets.filter(target => target.owner === this.id);
}
}
export default Group;
现在,组一个小组是一个丑陋的功能。我宁愿通过
new Group({title: 'test', isPublic: false, owner: 'me'})
而不是new Group('test', false, '', [], 'me')。
有没有更好的方法来编写这个不会导致一堆:
this.title = title;
this.isPublic = isPublic;
this.comments = comments;
...
看来我可以做到:
export class Group {
title: string;
isPublic: boolean;
comment: string;
targets: Target[];
owner?: string;
id?: string;
constructor({
title,
isPublic = false,
comment = '',
targets = [],
owner,
id,
}: {
title: string;
isPublic: boolean;
comment: string;
targets: Target[];
owner?: string;
id?: string;
}) {
this.title = title;
this.isPublic = isPublic;
this.comment = comment;
this.targets = targets;
this.owner = owner;
this.id = typeof id === 'undefined' ? uuid() : id;
}
但是我必须单独分配每个属性,有没有办法解决这个问题?
【问题讨论】:
标签: typescript