代码之家  ›  专栏  ›  技术社区  ›  mwilson

TypeScript—“新建”一个更好的类?

  •  1
  • mwilson  · 技术社区  · 8 年前

    interface IPerson {
      firstName: string;
      lastName: string;
      fullName: string;
    }
    
    class Person implements IPerson {
      public firstName: string;
      public lastName: string;
      public fullName: string;
      constructor(_firstName: string, _lastName: string) {
        this.firstName = _firstName;
        this.lastName = _lastName;
        this.fullName = `${this.firstName} ${this.lastName}`;
      }
    }
    

    然后我最终调用一些api来返回一些json。

    {
        "data": [
        {
          “firstName”: “John”,
          “lastName”: “Doe”
        },
        {
          “firstName”: “Jane”,
          “lastName”: “Doe”
        }
      ]
    }
    

    在得到回复后,我会通过做一些简单的事情来“重新开始”,比如:

    return response.data.map( d => new Person(d.firstName, d.lastName));

    我的问题:

    我有一些模型,它们有相当大的属性集,并且似乎非常冗余,将它们作为参数传递进来,并将它们绑定到各自的属性(至少感觉上是这样)。有没有更优雅的方法?

    我看到了许多与下面的示例类似的东西,但它们似乎都不是类中对象的“新成员”,因此它的行为正确(即:连接firstName和lastName)。

    类似的文章似乎提到了这样的事情:

    var modal: IModal = {
        content: '',
        form: '',
        href: '',
        $form: null,
        $message: null,
        $modal: null,
        $submits: null
    };
    

    其他人提到了一些类似的事情:

    modal: IModal = <IModal>{}
    

    或

    var modal = {} as IModal 
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Robert Stiffler    8 年前

    编写一个接受 IPerson

    interface IPerson {
      firstName: string;
      lastName: string;
      fullName: string;
    }
    
    class Person implements IPerson {
      public firstName: string;
      public lastName: string;
      public fullName: string;
      constructor(_firstName: string, _lastName: string) {
        this.firstName = _firstName;
        this.lastName = _lastName;
        this.fullName = `${this.firstName} ${this.lastName}`;
      }
      public static fromIPerson(person: IPerson): Person {
        return new Person(person.firstName, person.lastName);
      }
    }
    
        2
  •  2
  •   Hikmat G.    8 年前

    你可以用 Object.assign 为了避免每次都列出属性,而是使用数据对象本身- example

    更新:

    function filter(obj, data) {
      return Object.getOwnPropertyNames(obj).reduce((acc, k) => {
        acc[k] = data[k];
        return acc;
      }, {})
    }
    
    class Person implements IPerson {
      public firstName: string = "";
      public lastName: string = "";
      public get fullName(): string {
        return `${this.firstName} ${this.lastName}`;
      }
      constructor(data) {
        Object.assign(this, filter(this, data))
      }
    
    }