【问题标题】:Typescript constructor which takes object instead of parameters采用对象而不是参数的打字稿构造函数
【发布时间】: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


    【解决方案1】:

    您可以将接口定义为数据传输对象,也就是说并将其作为构造函数传入。

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

    【讨论】:

      猜你喜欢
      • 2018-06-26
      • 2018-07-15
      • 2023-03-03
      • 2019-04-29
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      相关资源
      最近更新 更多