带对象而不是参数的Typescript构造函数

时间:2020-03-30 21:14:23

标签: typescript

我的构造函数开始变长,而且不太像我喜欢的样子。我希望将一个对象传递给构造函数,以便可以按名称引用字段。这是现在的课程。

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;
  }

但是我必须分别分配每个属性,对此有办法吗?

1 个答案:

答案 0 :(得分:0)

您可以将接口定义为“数据传输对象”,以便说出来并将其作为构造函数传递。

interface IGroupDto {
  title: string;
  isPublic: boolean;
  comment: string;
  targets: Target[];
  owner?: string;
  id?: string;
}

export class Group {
  group: IGroupDto;
  constructor(group: IGroupDto) {
    // ...from here handle initialization of what you need from the data object
    // or maybe the `Group` class just has a property that contains the constructor object
    // below the `id` assignment is handled, de-structuring the data object 
    // last will override the id set from uuid(). or you can do it similar to how you did
    this.group = {id: uuid(), ...group}
  }
}