繁体   English   中英

使用对象而不是参数的打字稿构造函数

[英]Typescript constructor which takes object instead of parameters

我的构造函数开始变长,不像我喜欢的那样。 我更愿意将一个对象传递给我的构造函数,以便我可以按名称引用字段。 现在上课了。

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

但是我必须单独分配每个属性,有没有办法解决这个问题?

您可以将接口定义为数据传输对象,因此可以将其作为构造函数传入。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM